实体类映射在hibernate中,复杂的关系

时间:2014-05-16 13:17:20

标签: 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 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

}

这里A和B之间的关系是一对多,B到C是一对多,B到D是一对多,C到D是一对多。

List仅用于跟踪对象之间的顺序。但我也想跟踪B类中c和d列表的顺序。

B can have following steps:
 1. C1
 2. D1
 3. c2
 4. D2

使用当前设计,我无法在c和d之间存储订单。

请提出一些设计。谢谢

1 个答案:

答案 0 :(得分:2)

您可以从抽象实体继承CD,并使用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;     
    // ...
}

最后:

@Entity
public class B {
    Integer id;
    List<X> listOfX; // single list for C and D
}

看看inheritance stategies。在我的例子中,我使用单表策略。

另请查看this

显然你需要添加关系注释。