我正在尝试使子类的外键自动获取其父级的id。
儿童班:
public class Child implements Serializable
{
// primary (composite) key
private int parentId; // I want this to be set automatically
private String name;
// random value
private String val;
public Child(String name, String val) {
this.name = name;
this.val = val;
}
public void setParentId(int id) {
[...]
}
父xml:
<map name="children" inverse="true" lazy="true" cascade="all,delete-orphan">
<cache usage="nonstrict-read-write"/>
<key column="parent_id"/>
<index column="child_name" type="string"/>
<one-to-many class="myPack.Child"/>
</map>
儿童xml:
<class name="Child" table="child_tbl" lazy="true">
<composite-id>
<key-property name="ParentId" type="int" column="parent_id"/>
<key-property name="Name" column="name" type="string"/>
<generator class="foreign">
<param name="property">ParentId</param>
</generator>
</composite-id>
<property name="Val" blablabla
[...]
然而它失败了:
HibernateException:无法解析属性:ParentId
Hibernate是否支持复合ID上的外部生成器?或者是父类认为Map存在问题?
答案 0 :(得分:1)
我自己尝试过,它对我有用
请注意,子类必须实现equals()
和hashCode()
方法。
public class Parent {
private int id;
private String name;
//...getter setter methods
}
public class Child implements Serializable{
private Parent parent;
private String name;
public boolean equals(Object c){
//implement this
}
public int hashCode(){
//implement this
}
//..getter setter methods
}
注意:
many-to-one
映射设置为unique="true"
,表示one-to-one
关系insert="false"
和update="false"
因为该列被用作composite-id
。 子类映射:
<class name="Child" table="CHILD" dynamic-update="true">
<composite-id>
<key-property name="name"></key-property>
<key-many-to-one name="parent" class="Parent" column="id"/>
</composite-id>
<many-to-one name="parent" class="Parent"
unique="true" column="id" insert="false" update="false" />
</class>