【问题标题】:Hibernate composite-key and foreign generatorHibernate 复合键和外部生成器
【发布时间】:2011-12-05 08:59:56
【问题描述】:

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

【问题讨论】:

    标签: hibernate generator


    【解决方案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
    }
    

    休眠映射

    注意:

    1. 未显示父级映射
    2. Child 和 Parent 之间的 many-to-one 映射设置为 unique="true",表示 one-to-one 关系
    3. 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>
    

    【讨论】:

      猜你喜欢
      • 2011-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 1970-01-01
      • 2018-01-07
      • 1970-01-01
      • 2014-02-26
      相关资源
      最近更新 更多