欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

JPA注解实现one-to-one的主键关联映射

发布时间:2023/12/15 48 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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的主键关联映射的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。