2012-05-30 39 views
0

我正試圖對一個表執行一個自引用映射(父/子樣關係)映射。基於外鍵值Hibernate ORM映射的歧視

我想要的是來自同一張表的兩個不同的實體,以便我可以分開屬性等等。我正在考慮使用鑑別器值,但我不能這樣做,因爲我的數據庫已經被定義爲以下內容:爲了區分父對象和子對象,我們有parent_id對於子類型不爲null(parent_id當然是外鍵到同一張桌子)。無法通過以下方式定義鑑別器值:如果對象是父類型,則鑑別器值爲null否則爲child。

我正在尋找解決方案,我有點卡住了。也許,我將最終使用一個實體,它帶有兩個引用父對象的屬性(對於child,@ManyToOne不是null)和子對象列表(對於子對象,@OneToMany爲null)。但在此之前(現在,我必須決定使用一個實體),我想問一下是否有工作來執行我正在嘗試做的事情。

回答

1

鑑別器可以是一個「公式」。這完全是Hibernate特性,並且不受JPA支持。你可以使用@ org.hibernate.annotations.DiscriminatorFormula,是這樣的:

@Entity 
@Inheritance(strategy=SINGLE_TABLE) 
@DiscriminatorFormula("case when parent_id is null then 'PARENT' ELSE 'CHILD' end") 
@DiscriminatorValue("PARENT") 
public class Parent { 
    ... 
} 

// map Child using @DiscriminatorValue("CHILD") 
+0

謝謝您的回答。直到現在我還沒有意識到這個功能。這正是我所期待的。到目前爲止,我們只被允許使用JPA支持的Hibernate特性,我希望這可能是個例外。無論如何,我認爲從現在開始,我將在我的個人項目中使用此功能。再次謝謝你! – aslan

+0

然後把這個標記爲正確的答案;) –

+0

對不起,我忘了它:)現在它完成了再次感謝! – aslan

0

另一種解決方案是利用特殊的hibernate值@DiscriminatorValue("null")@DiscriminatorValue("not null")

@Entity 
@Inheritance(strategy=SINGLE_TABLE) 
@DiscriminatorColumn("parent_id") 
@DiscriminatorValue("null") 
public class Parent { 
    ... 
} 

@Entity 
@DiscriminatorValue("not null") 
public class Child extends Parent { 
    ... 
}