Hibernate exception while saving with cascade=“save-update”

前端 未结 3 1964
梦如初夏
梦如初夏 2021-01-25 05:04

Here is my hbm and test code respectively. I am using Spring\'s HibernateTemplate. I doesn\'t use DAO. Hibernate 2.2.5 with Spring 2.0.7

hbm

<         


        
相关标签:
3条回答
  • 2021-01-25 05:08

    since instances of the same class are both parents and children, you need an id, which you have, but you also need a parent-id type column in the db (and field on the class) so the children can have a reference to their parent.

    See https://forum.hibernate.org/viewtopic.php?f=1&t=1004163

    0 讨论(0)
  • 2021-01-25 05:11

    Ok the root cause was the invalid mapping on my part for the collection. Thanks to this article on composite mapping

    Wrong:

    <key>
      <column name="ID" />
    </key>
    

    Correct

    <many-to-one name="parent" class="Product" lazy="false" column="PARENT" />
    
    <set name="children" lazy="false" fetch="join" table="PRODUCT" cascade="all">
      <key>
        <column name="PARENT" />
      </key>
      <one-to-many class="Product" />
    </set>
    

    Complete mapping

    <class name="Product" table="PRODUCT">
            <id name="id" type="java.lang.Long" column="ID">
                <generator class="native">
                    <param name="sequence">PRODUCT_SN</param>
                </generator>
            </id>
    
            <many-to-one name="parent" class="Product" lazy="false" column="PARENT" />
    
            <set name="children" lazy="false" fetch="join" table="PRODUCT" cascade="all">
                <key>
                    <column name="PARENT" />
                </key>
                <one-to-many class="Product" />
            </set>
            <property name="code" type="java.lang.String" column="CODE" not-null="true" />
            <property name="name" type="java.lang.String" column="NAME" />
            <property name="startDate" type="java.util.Date" column="STARTDATE" />
            <property name="endDate" type="java.util.Date" column="ENDDATE" />
            <property name="decisionable" type="boolean" column="ISDECISIONABLE" />
            <property name="selectable" type="boolean" column="ISSELECTABLE" />
        </class>
    
    0 讨论(0)
  • 2021-01-25 05:12

    When you made a bidirectional relationship you need to put inverse=true otherwise hibernate is going to try to do a double access and that is why you are getting a exception. Hibernate needs to know which side of the relationship is the one who has the control of saving and updating.

    0 讨论(0)
提交回复
热议问题