开发者

Hibernate composite-key and foreign generator

开发者 https://www.devze.com 2023-04-12 01:06 出处:网络
I\'m trying to make a foreign key of a child class automatically get the id of it\'s parent. Child class:

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 :

  1. mapping for parent is not shown
  2. the many-to-one mapping between Child and Parent is set to unique="true" indicating one-to-one relation
  3. insert="false" and update="false" as the column is being used as composite-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>
0

精彩评论

暂无评论...
验证码 换一张
取 消