3

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?

dodoptak
  • 69
  • 1
  • 6

1 Answers1

3

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;
}
Cyril Maitre
  • 401
  • 3
  • 6
  • Should key class be named `TextKey` instead of `LabelRepositoryKey`? – dodoptak Jul 19 '18 at 14:15
  • I would say no since this is the key of a LabelRepository entry. – Cyril Maitre Jul 19 '18 at 14:24
  • But then I would have to modify the `Text` entity, because for now there is only one primary key and I would not be able to insert to the table two entries with the same id (constraint - `id` and `language_id` should be together unique) – dodoptak Jul 19 '18 at 14:42