码迷,mamicode.com
首页 > 系统相关 > 详细

Rhythmk 学习 Hibernate 08 - Hibernate annotation 关联关系注解

时间:2014-05-03 22:28:15      阅读:420      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   tar   

1、一对一 (One to One)
    共三种情况:
     1.1 主键共享
    1.2 外键共享

    1.3 中间表关联

1.1  code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Entity
public class article {
    @Id
    @GeneratedValue
   public Integer getArticleId() {
        return articleId;
    }
    .....
    @OneToOne(cascade=CascadeType.ALL)
    @PrimaryKeyJoinColumn
        public articleContent getContent() {
        return content;
    }
    ......
}
1
2
3
4
5
6
7
8
9
10
@Entity
public class articleContent  {
     
    @Id
    @GeneratedValue
    public Integer getcId() {
        return cId;
    }
    ....
}

  执行保存 生成两张无外键的独立表

1.2  code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Entity
public class article {
     
    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="cid_fk")
        public articleContent getContent() {
        return content;
    }
     
}
 
@Entity
public class articleContent  {
     
    @OneToOne(mappedBy="articleContent")
    public article ArticleEntity;
}

  执行保存,生成两张表,同时article生成一个cid_fk字段 关联 articleContent主键ID

1.3  code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Entity
public class article {
    @Id
    @GeneratedValue
   public Integer getArticleId() {
        return articleId;
    }
 
    @OneToOne(cascade=CascadeType.ALL)
    @JoinTable(name="article_content",
          joinColumns=@JoinColumn(name="aid"),
          inverseJoinColumns=@JoinColumn(name="aid_fk"))
        public articleContent getContent() {
        return content;
    }
    ......
}

  生成三张表 分别为:article,article_content,articlecontent  其中 article_content 分别生成两个外键具体参考等价建表语句:

1
2
3
4
5
6
7
8
CREATE TABLE `article_content` (
  `aid_fk` int(11) DEFAULT NULL,
  `aid` int(11) NOT NULL,
  PRIMARY KEY (`aid`),
  KEY `FK_7pgn2vn8r1lpswmh5v2ix667s` (`aid_fk`),
  CONSTRAINT `FK_ebfc4cs1sishg6u8kwpvgqqj9` FOREIGN KEY (`aid`) REFERENCES `article` (`articleId`),
  CONSTRAINT `FK_7pgn2vn8r1lpswmh5v2ix667s` FOREIGN KEY (`aid_fk`) REFERENCES `articlecontent` (`cId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  

 

Rhythmk 学习 Hibernate 08 - Hibernate annotation 关联关系注解,布布扣,bubuko.com

Rhythmk 学习 Hibernate 08 - Hibernate annotation 关联关系注解

标签:style   blog   class   code   java   tar   

原文地址:http://www.cnblogs.com/rhythmK/p/3705259.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!