Java hibernate中的实体类映射,复杂关系
我有四个类(A、B、C、D),它们都是通过关系连接起来的。我正在使用hibernate将它们存储在mysql数据库中 班级结构Java hibernate中的实体类映射,复杂关系,java,hibernate,jpa,database-design,persistence,Java,Hibernate,Jpa,Database Design,Persistence,我有四个类(A、B、C、D),它们都是通过关系连接起来的。我正在使用hibernate将它们存储在mysql数据库中 班级结构 Class A { Integer id; //primary key List<B> listOfB; //one to many with B class, able to store order of B's //some other fields } /* This class can con
Class A {
Integer id; //primary key
List<B> listOfB; //one to many with B class, able to store order of B's
//some other fields
}
/* This class can contain list of c, or list of d, or both.
* need to keep order among c and d also if contains both list
* for eg, B has list of c(c1, c2, c3) and D (d1, d2, d3)
* order can be c1, d1, c2, d3, c3, d2
*/
Class B {
Integer id; //primary key
List<C> listOfC; //one to many with D class, able to store order of C's
List<D> listOfD; //one to many with C class, able to store order of D's
//How to store order between list of c and list of d?
//some other field
}
Class C {
Integer id; //primary key
List<D> listOfD; //one to many with D class, able to store order of D's
//some other field
}
Class D {
Integer id; //primary key
String value; //some value
}
按照目前的设计,我无法存储c和d之间的订单
请提出一些设计建议。谢谢您可以从抽象实体继承
C
和D
,并在B
中使用单个列表
抽象实体:
@Entity
@Inheritance
@DiscriminatorColumn(name = "discr")
public abstract class X {
Integer id;
// ...
}
然后扩展它:
@Entity
@DiscriminatorValue("c")
public class C extends X {
List<D> listOfD;
// ...
}
@Entity
@DiscriminatorValue("d")
public class D extends X {
String value;
// ...
}
@实体
@鉴别器值(“c”)
公共类C扩展X{
清单D;
// ...
}
@实体
@鉴别器值(“d”)
公共类D扩展了X{
字符串值;
// ...
}
最后:
@Entity
public class B {
Integer id;
List<X> listOfX; // single list for C and D
}
@实体
公共B级{
整数id;
List listOfX;//C和D的单个列表
}
看一看。在我的示例中,我使用单表策略
也看看
显然,您需要添加关系注释。但是hibernate如何将它们存储在db中呢?C和D的结构可以是different@Raj看看Hibernate文档(答案中的链接)。您可以有多个表(每种类型一个),也可以只有一个表(包含所有字段的表)和一个鉴别器列。
@Entity
public class B {
Integer id;
List<X> listOfX; // single list for C and D
}