【问题标题】:Spring JPA - entity with two primary keySpring JPA - 具有两个主键的实体
【发布时间】:2018-12-27 15:04:35
【问题描述】:

LabelTextLanguage三个表:

@Entity
public class Label {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    @JoinColumn(name = "text_id")
    private Text text;

}

然后是文字:

@Entity
public class Text {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "text", columnDefinition = "TEXT")
    private String text;

    @OneToMany(mappedBy = "text")
    private List<Label> labels;

    @ManyToOne
    @JoinColumn(name = "language_id")
    private Language language;

}

最后:

@Entity
public class Language {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "code")
    private String code;

    @OneToMany(mappedBy = "language")
    private List<Text> texts;

}

Text 实体中拥有两个键text_idlanguage_id 的最佳方法是什么,它们应该是唯一的,例如文本表如下所示:

text_id     language_id     text
------------------------------------
1           1               Example
1           2               Beispiel

然后在LabelRepository 中,我将能够定义我想要文本的哪种语言?

【问题讨论】:

    标签: java spring-data-jpa


    【解决方案1】:

    您可以在这里找到两个解决方案:How to create and handle composite primary key in JPA

    • 第一个基于@Embeddable 类。
    • 第二个基于@IdClass 类。

    @IdClass 解决方案总结:

    1- 创建一个“关键”类

    public class LabelRepositoryKey implements Serializable {
      private Long textId;
      private Long languageId;
    }
    

    2- 然后,在您的实体中使用这个“关键”类

    @Entity @IdClass(LabelRepositoryKey.class)
    public class LabelRepository {
      @Id
      private Long textId;
      @Id
      private Long languageId;
      @Column(name = "text")
      private String text;
    }
    

    【讨论】:

    • 应该将密钥类命名为TextKey 而不是LabelRepositoryKey
    • 我会说不,因为这是 LabelRepository 条目的键。
    • 但是我必须修改 Text 实体,因为现在只有一个主键,我无法向表中插入两个具有相同 id 的条目(约束 - idlanguage_id 应该是唯一的)
    猜你喜欢
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 2013-08-26
    • 2014-02-19
    • 2013-12-24
    • 2021-02-25
    相关资源
    最近更新 更多