Hibernate composite-key and foreign generator
I'm trying to make a foreign key of a child class automatically get the id of it's parent.
Child class:
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) {
[...]
}
Parent 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>
Child xml:
<class name="Child" table="child_tbl" lazy="true">
<composi开发者_如何学JAVAte-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
[...]
However it fails with:
HibernateException: Unable to resolve property: ParentId
Does Hibernate support foreign generators on composite-ids? Or is the fact that the parent class holds a Map an issue?
I tried this myself and it worked for me
Class Definition
Note that the child class has to implement equals()
and hashCode()
methods.
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
}
Hibernate Mapping
Note :
- mapping for parent is not shown
- the
many-to-one
mapping between Child and Parent is set tounique="true"
indicatingone-to-one
relation insert="false"
andupdate="false"
as the column is being used ascomposite-id
.
Child class mapping:
<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>
精彩评论