How to join more tables to the same id (FK)?

I have 4 tables:

Table1

  • Id1 → PK
  • Name1

Table2

  • Id2 → PK
  • Name2

Table3

  • Id3 → PK
  • Name3

Table4

  • Id1 → PK → FK to table1.id1
  • Id_link → PK → FK to table2.id2
  •           -> FK to table3.id3
    
  • name

I have:

  • One2Many between Table1 and Table4, on id1,
  • Many2One between Table4 and Table2 on id_link
  • Many2One between Table4 and Table3 on id_link

How should I do the mapping between the JPA entities?

Hi Monky,

please understand that this is a forum for questions, but your request seems like you want someone else to do your work. I understand that this kind of mapping is not trivial, but there are many similar questions on the web if you search for “composite many-to-one”. Usually, people ask specific questions because they tried something which didn’t work the way they expect. I will do the work for you this time, but beware that you might not receive answers if your request/question is too broad, like this one. Unless you build up an understanding for the possible mappings (by reading a book or tutorials) you will most likely run into the next issue very soon, so I recommend you first try to get familiar with the possibilities before thinking about your concrete model.

@Entity
public class Table1 {
  @Id
  @GeneratedValue
  Long id;
  String name;
  @OneToMany(mappedBy = "table1")
  Set<Table4> table4s;
}
@Entity
public class Table2 {
  @Id
  @GeneratedValue
  Long id;
  String name;
}
@Entity
public class Table3 {
  @Id
  @GeneratedValue
  Long id;
  String name;
}
@Entity
public class Table4 {
  @EmbeddedId
  Table4Id id;
  @ManyToOne(fetch = LAZY)
  @JoinColumn(name = "id1", insertable = false, updatable = false)
  Table1 table1;
  @ManyToOne(fetch = LAZY)
  @JoinColumn(name = "id_link", insertable = false, updatable = false)
  Table2 table2;
  @ManyToOne(fetch = LAZY)
  @JoinColumn(name = "id_link3")
  Table3 table3;
  String name;
}

@Embeddable
public class Table4Id {
  @Column(name = "id1")
  Long id1;
  @Column(name = "id_link")
  Long idLink;
}

Thank you for your answer.
I searched a lot for a solution, but got error: “Repeted column in mapping”, so this post was a last hope.
The issue here is mainly the link between both Table2 (pk=id2) and Table3 (pk=id3) on the SAME column in Table4: “id_link” (there is no “id_link3” column).

The problem about the repeated column in mapping, if you search for that error, is that multiple attributes in your entities could be the source for writing the column, which is unsupported. This is where the insertable = false, updatable = false bits help.