无法使用Hibernate Table Per Class Hierarchy查询获取子类值

时间:2015-07-09 20:25:17

标签: java hibernate class

我有2个带有hibernate定义类的java类,它们定义父/子关系,并为单个表定义“extends”关键字。 我在表中有一个LONGTEXT字段,用于定义记录与之关系的子类的类型。 (每个类层次结构的表)

我想查询表并将与特定子类关联的记录放入子类对象中。

我尝试将记录列表检索到父类列表中,并将它们从父对象转换为具有子转换的子对象,但当然,Java在运行时不允许这样做。 (虽然在编译时看起来很漂亮)

我还尝试将子类查询到子类列表中,但唯一具有值的属性是子类中的属性。即使子项扩展了父类,对应于父类的所有属性都为null。

如何将表查询到扩展子类。在我这样做之后,我需要访问子类的成员。

@DBTableMap ( dbTable = "TABLE_MINE", dbTableAlias = "tableDef" )
public class ParentDefined extends BaseData {

@DBPrimaryKey ( dbColumn = "id" )
private Long id;
private String type;
....
}

@DBTableMap ( dbTable = "TABLE_MINE", dbTableAlias = "tableDef", includeParent = true )
public class ChildDefined extends ParentDefined {

public ChildDefined()
{
    setDiscriminator("a type 1");
}

private String name;
private String overrideName;

public String getName() {
    return name;
}
public void setName(String name) {
    name = name;
}
public String getOverrideName() {
    return overrideName;
}
public void setOverrideName(String overrideName) {
    this.overrideName = overrideName;
}

}

<hibernate-mapping>

<subclass name="ChildDefined" 
      extends="ParentDefined"
      type-value="a type 1">

    <property name="name" column="name" type="string" not-null="false"/>
    <property name="overrideName" column="overrideName" type="string"/>
</subclass>
</hibernate-mapping>

<hibernate-mapping>

<class name="ParentDefined" 
      table="TABLE_MINE" 
      abstract="true" 
      type-value="0">

    <id name="id" column="id">
        <generator class="native"/>
    </id>
<type column="type" type="string" length="256" not-null="true"/>
    </class>

List<ParentClass> parents = (query using parent class by id);
for(ParentDefined parent : parents){
     ChildDefined child = (ChildDefined) parent; //class cast exception
}

List<ChildClass> childs = (query using child class by id and type 1);
for(ChildDefined child : childs){
     child; //class object only has values in ChildDefined members. Members of ParentDefined are null;
}

0 个答案:

没有答案