如何在hibernate中使用单个表连接三个表? [英] How to join three tables using a single table in hibernate?
问题描述
我有三张桌子 A
, B
和 C
和一个映射表 A_B_C
,其中包含所有三个表和一些其他属性的外键(假设 X
, ý
)。现在,我想加入在我的java类中表示这三个表。
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.
这些表之间的关系是一对多的。因此,我希望我的Java类看起来像这样。
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 {
...
}
我想知道是否可以利用Hibernate Annotations 。如果没有,有没有办法可以编写自定义查询并填充变量?
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?
推荐答案
不幸的是,hibernate没有为这种情况提供开箱即用的任何注释。此方案只能通过创建映射到 A_B_C
的类来处理:
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.
}
并在A中有一个这个对象的列表:
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.
}
以编程方式将Set abc转换为 B,C
的地图。
And programmatically convert the Set abc to a map of B,C
.
这篇关于如何在hibernate中使用单个表连接三个表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!