Sleeping combination key and external generator

I am trying to make the foreign key of a child class automatically to get its parent id.

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

    [...]
}

Xml parent:

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

    <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
[...]

However, this fails:

HibernateException: Cannot resolve property: ParentId

Does Hibernate support external generators on compound identifiers? Or the fact that the parent class contains a map?

0
source share
1 answer

I tried it myself and it worked for me

Class definition

Note that the child class must implement the equals()and methods 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
}

Hibernation display

Note:

  • parent display is not displayed
  • many-to-one unique="true", one-to-one
  • 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>
+1

All Articles