如何在hibernate中使用子类来表示表中的属性?

时间:2012-04-20 08:15:32

标签: java hibernate hibernate-mapping

我有以下域对象

Loan {
     int id;
     Date attribute1;
}

LoanExtension {
     Date attribute2;
}

我想保留我的对象,因为有时我想只更改数据库中LoanExtension中的属性(即loan对象中的attribute1在对象中将为null,我不希望它被设置为在数据库中)。

使用xml的hibernate映射怎么可能?我做了以下

<class name="org.domain.borrowerReview.Loan" table="loan_profiles" >
    <cache usage="read-only"/>
    <id name="loanId" column="id">
        <generator class="native"/>
    </id>
    <version name="attribute1" column="date_1/>
    <subclass name="org.domain.borrowerReview.LoanExtension" extends="org.rangde.domain.borrowerReview.LoanProfilesUpdate">
        <property name="attribute2" column="date_2" />
    </subclass>
</class>

我遇到了这个例外: 当使用'single-table-per-hierarchy'并且类具有子类

时,需要使用判别器

1 个答案:

答案 0 :(得分:0)

简短回答

您需要添加一个鉴别器列并将代码段更改为此类内容。

<class name="org.domain.borrowerReview.Loan" table="loan_profiles" > 
    <cache usage="read-only"/> 
    <id name="loanId" column="id"> 
        <generator class="native"/> 
    </id> 
    <version name="attribute1" column="date_1/> 
    <discriminator column="loan_profiles_type" type="string"/>
    <subclass name="org.domain.borrowerReview.LoanExtension" extends="org.rangde.domain.borrowerReview.LoanProfilesUpdate"> 
        <property name="attribute2" column="date_2" /> 
    </subclass> 
</class> 

答案很长

首先,请记住JPA中的继承不是与常规继承的绝对并行。

必须评估类的设计如何影响底层架构。

您尚未提及如何将表结构设为。

Hibernate提供了三种继承机制。

  • 每个类层次结构的表
  • 每个子类的表
  • 每个具体类的表

见详情here

您的xml代码段表明您正在使用每个类层次结构的表。

现在,如果有一个子类,如果只是一个子类(虽然它是允许的),几乎没有用处。在“每个类层次结构表”下,所有子类都放在同一个表中。

为了区分特定记录属于哪个子类,hibernate依赖于鉴别器列。

您需要定义相同的内容。

请参阅以下文档documentation