Rhythmk 学习 Hibernate 08 - Hibernate annotation 关联关系注解
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 关联关系注解,古老的榕树,5-wow.com
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。