【问题标题】:What is the correct data type for JpaRepository that has Primary Key but it is also a Foreign Key?具有主键但也是外键的 JpaRepository 的正确数据类型是什么?
【发布时间】:2021-02-20 21:55:19
【问题描述】:

我有以下表格,

User
int id PK

Contact
int id PK, FK to User.id

所以我在Contact.java的代码如下,

@Getter(value = AccessLevel.NONE)
@Setter(value = AccessLevel.NONE)
@Id
@Column(name = "id", insertable = false, updatable = false)
private Integer id;

@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JoinColumn(name = "id", nullable = false)
private User userId;

在我的User.java 中有,

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

所以根据上面的代码,我有一些疑问。

  1. 这是指示联系人的 id(主键)也是用户的外键的正确方法吗?

  2. 我需要使用@PrimaryKeyJoinColumn 还是@JoinColumn

  3. 根据上面的代码,我的仓库界面应该是怎样的?

     public interface ContactRepository extends JpaRepository<Contact, User> {}
    

     public interface ContactRepository extends JpaRepository<Contact, Integer> {}
    

【问题讨论】:

    标签: java spring-boot hibernate spring-data-jpa jpa-2.0


    【解决方案1】:
    1. 如果可以,不要使用外键作为主键
    2. 加入列
    3. 合同有整数ID,所以&lt;Contact, Integer&gt;

    【讨论】:

    • 非常感谢您的回答和您的时间。
    猜你喜欢
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 2019-12-25
    • 2018-08-20
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    相关资源
    最近更新 更多