首页 > 解决方案 > 具有主键但也是外键的 JpaRepository 的正确数据类型是什么?

问题描述

我有以下表格,

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. 我需要使用@PrimaryKeyJoinColumnor@JoinColumn吗?

  3. 根据上面的代码,我的存储库接口应该是怎样的?

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

    或者

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

标签: javaspring-boothibernatespring-data-jpajpa-2.0

解决方案


  1. 不要使用外键作为主键,如果使用可以
  2. 加入专栏
  3. 合同有整数 id,所以<Contact, Integer>

推荐阅读