Home » Java » Spring JPA – entity with two primary key

Spring JPA – entity with two primary key

Posted by: admin September 26, 2018 Leave a comment

Questions:

There are 3 tables Label, Text and Language:

@Entity
public class Label {

    @Id
    @GeneratedValue
    private Long id;

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

}

Then 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;

}

And finally:

@Entity
public class Language {

    @Id
    @GeneratedValue
    private Long id;

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

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

}

What is the best approach to have in the Text entity two keys text_id and language_id that together should be unique and for example Text table would look like this:

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

And then in LabelRepository I would be able to define for which language I would like the text?

Answers: