2014-05-16 60 views
0

我有四個類(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是一對多的。

列表僅用於跟蹤對象之間的順序。但是我也想跟蹤B類中c和d列表的順序。

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

在目前的設計中,我無法存儲c和d之間的順序。

請建議一些設計。謝謝

回答

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

顯然,你需要添加關係註解。

+0

但hibernate將如何將它們存儲在數據庫? C和D的結構可以不同 – Manish

+0

@Raj看一下Hibernate文檔(答案中的鏈接)。你可以有幾個表格(每種類型一個表格),或者只有一個表格包含所有的字段,還有一個鑑別器列。 – davioooh

+0

謝謝我會閱讀並嘗試 – Manish