本文介绍了休眠复合密钥和外来生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图为子类的外键自动获取其父类的ID.
I'm trying to make a foreign key of a child class automatically get the id of it's parent.
儿童班:
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
[...]
但是它失败了:
Hibernate是否支持复合ID上的外部生成器?还是父类持有Map的事实?
Does Hibernate support foreign generators on composite-ids? Or is the fact that the parent class holds a Map an issue?
推荐答案
我自己尝试过,对我有用
请注意,子类必须实现equals()
和hashCode()
方法.
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
}
休眠映射
注意:
- 未显示针对父级的映射
- 将子级与父级之间的
many-to-one
映射设置为unique="true"
,指示one-to-one
关系 -
insert="false"
和update="false"
作为列被用作composite-id
.
- 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
.
子类映射:
<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>
这篇关于休眠复合密钥和外来生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!