I need to join 3 tables where A.id == B.id and B.id == C.id using JPA @SecondaryTables where I need to map these tables to a single entity. what is the way I should I should try?


Since A.ID = B.ID = C.ID, you can just have 2 secondary tables, with the relationship A.ID = B.ID, and A.ID = C.ID. Your "main" table will be A, and B and C are your secondary tables. You can reference the table as follows in your column declaration. (many other parameters in the annotations left out for brevity)

@Table(name = "A")
  @SecondaryTable(name="B", @PrimaryKeyJoinColumn(name="ID", referencedColumnName="ID")),  
  @SecondaryTable(name="C",  @PrimaryKeyJoinColumn(name="ID", referencedColumnName="ID"))
public Claass Blah {
  private int id;

  @Column(table = "B")
  private String someColumn;

  @Column(table = "C")
  private String someOtherColumn;

  • I have tried that but C.id is referencing to A.id. It is like this A.id = B.id and A.id = C.id what I need is A.id == B.id and B.id == C.id – Jayampathy Wijesena Mar 15 '18 at 4:29
  • 1
    I'm not understanding you. If A.id = B.id, and B.id = C.id, then by transitivity, A.id = C.id – Jeff Wang Mar 15 '18 at 5:31
  • yes that is correct but what I need is something like this A.id = B.id and B.did = C.did There is no relationship like A.id = C.id – Jayampathy Wijesena Mar 15 '18 at 5:39
  • I see, so the id for the two relationships is separate? Do you have to have the same class? If not, you can create 2 classes, one of which has a secondary table, the other of which has a @OneToOne relationship with the first one. – Jeff Wang Mar 15 '18 at 6:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.