Hibernate复合键和外部生成器

时间:2011-10-11 14:29:52

标签: hibernate generator

我正在尝试使子类的外键自动获取其父级的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存在问题?

1 个答案:

答案 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
}

Hibernate Mapping

注意:

  1. 未显示父项的映射
  2. Child和Parent之间的many-to-one映射设置为unique="true",表示one-to-one关系
  3. insert="false"update="false"因为该列被用作composite-id
  4. 子类映射:

    <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>