简体   繁体   中英

How to join three tables using a single table in hibernate?

I have three tables A , B and C and a mapping table A_B_C which has foreign keys to all the three tables and some other attributes (let's say X , Y ). Now, I want to join represent these three table in my java class.

The relationship between these tables are one to many. Hence, I want my Java classes to look something like this.

@Entity(name = "A")
@Table(name = "A")
public class A {

       ??? Hibernate Annotation or query
       Map<B,List<C>> BMapC;
}

@Entity(name = "B")
@Table(name = "B")
public class B {
      ...
}

@Entity(name = "C")
@Table(name = "C")
public class C {
      ...
}

I would like to know if it would be possible to leverage Hibernate Annotations for this. If not, is there a way I can write a custom query and populate the variable?

Unfortunately hibernate does not provide any annotations out-of-the-box for such scenarios. This scenario can only be handled by creating a class mapping to A_B_C :

@Entity
@Table(name = "A_B_C")
public class name = "A_B_C" {

     @ManyToOne(cascade=CascadeType.ALL)
     @JoinColumn(name = "FK_B", nullable = false)
     private B b;

     @ManyToOne(cascade=CascadeType.ALL)
     @JoinColumn(name = "FK_C", nullable = false)
     private C c;

     //Getters, Setters, other attributes etc.
} 

And have a list of this object in A:

 @Entity
 @Table(name = "A")
 public class name = "A" {

          @OneToMany(cascade=CascadeType.ALL)
          @JoinColumn(name = "FK_A", nullable = false)
          private Set<A_B_C> abc;

          //Getters, Setters, other attributes etc.
 } 

And programmatically convert the Set abc to a map of B,C .

I believe what you are looking for is more of a following

http://www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/

where a join table has an extra column

Hope this article helps

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM