dodoptak
dodoptak

Reputation: 69

Spring JPA - entity with two primary key

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?

Upvotes: 3

Views: 9146

Answers (1)

Cyril Maitre
Cyril Maitre

Reputation: 401

You can found two solutions here: How to create and handle composite primary key in JPA

  • The first one is based on a @Embeddable class.
  • The second one is based on a @IdClass class.

Summary of the @IdClass solution:

1- Create a "key" class

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

2- Then, use this "key" class in your entity

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

Upvotes: 3

Related Questions