Hibernate add relationship between two unrelated entities (not related by foreign key)


#1

Hi,

I don’t solve my problem with annotation hibernate.

I have 3 tables :

  • Table A (String id, String codeType , String idOther );
  • Table B (String id)
  • Table C (String id)

The attribute idOther of table A is not a foreign key because it can be referenced by multiples tables like table B or C.

The attribute idOther of table A is equals to identifiant of table C when codeType=“C” .

The attribute idOther of table A is equals to identifiant of table B when codeType=“B” .

With annotations of Hibernate, how can I etablish a relationship between entity A and entity C ?

@Entity("A")
public class A {
 
   @Id
   private String id;
   private String codeType;
   private String idOther;
} 
 
@Entity("B")
public class B {
 
   @Id
   private String id;
 
    /** what annotation to add for etablish a relationship */
   private A a;
} 
 
@Entity("C")
public class C {
 
   @Id
   private String id;
 
   /** what annotation to add for etablish a relationship */
   private A a;
}

Thanks for your answer.


#2

You achieve your goal with the @ManyToAny mapping. Check out the User Guide for a detailed example.


#3

Thanks vlad ! It solved my problem