JPA注解实现one-to-one的主键关联映射
作者:xyzroundo
假设两个数据表的主-从表:
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
实体配置如下:
@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很重要,它指定关联属性不能为空。只要设为false,生成的数据表的从表(Tb_ContactInfo)才会有外键约束
总结
以上是生活随笔为你收集整理的JPA注解实现one-to-one的主键关联映射的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 报告称美国电动车主去年充电失败率为 20
- 下一篇: ARP简介