JPA注解实现one-to-one的主键关联映射
作者:xyzroundo
?
假設(shè)兩個(gè)數(shù)據(jù)表的主-從表:
?
Tb_Account(.... , primary key (ac_id)),Tb_ContactInfo(..., primary key (ci_id))
?
alter table Tb_ContactInfo add constraint FKABAF989DFBC1A028 foreign key (ci_id) references Tb_Account
?
實(shí)體配置如下:
?
@Entity
@Table(name = "Tb_Account")
public class Account{
?? ? @Id
??? @Column(name = "ac_id", columnDefinition = "INT")
??? public Integer id;
......
??? @OneToOne(mappedBy="account")
??? private ContactInfo contact;
?? .....
}
?
?
@Entity
@Table(name = "Tb_ContactInfo")
public class ContactInfo {
??? @Id
??? @Column(name = "ci_id", columnDefinition = "INT")
??? private Integer id;
......
??? @OneToOne(optional=false)
??? @PrimaryKeyJoinColumn
??? private Account account;
??? ......
?
}
?
注:optional=false很重要,它指定關(guān)聯(lián)屬性不能為空。只要設(shè)為false,生成的數(shù)據(jù)表的從表(Tb_ContactInfo)才會(huì)有外鍵約束
總結(jié)
以上是生活随笔為你收集整理的JPA注解实现one-to-one的主键关联映射的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 报告称美国电动车主去年充电失败率为 20
- 下一篇: 史上最丝滑 长臂猿两秒进化成人:视觉错位