关于Hibernate多对多关联关系的更新问题。

一个账套类Reckoning和账套项目类 AccountItem。这两个类是双向多对多关联关系。

Reckoning.hbm.xml文件的配置如下

<set name="accountItems" table="ITEM_RECKONING"  lazy="true" >
            <key>
                <column name="R_ID"></column>
            </key>
            <many-to-many class="com.pms.entities.base.AccountItem" column="I_ID"></many-to-many>
        </set>

AccountItem.hbm.xml文件的配置如下:

<set name="reckonings" table="ITEM_RECKONING" inverse="true" lazy="false">
            <key>
                <column name="I_ID"></column>
            </key>
            <many-to-many class="com.pms.entities.treatmentManage.Reckoning" column="R_ID"></many-to-many>
        </set>

我在执行更新操作的时候一直都报如下的错误:检查了一遍又一遍,都没有找出错误,明明知道内存中存在了两个的ID相同的Reckoning,但就是不知道什么原因导致的。
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.pms.entities.treatmentManage.Reckoning#10]
直至目前,至于是什么原因还不太清楚。

以下个人猜测:应该是没有使用懒加载导致的。

因为我在进行Reckoning对象修改的操作的时候,我首先根据Reckoning的ID获取了Reckoning对象,但是我又需要获取AccountItem的集合,所以,我获取了所有的AccountItem对象。那么问题来了,因为AccountItem是不使用懒加载的。也就是说我获取了所有的AccountItem对象,那么这AccountItem对象又把它关联的Reckoning对象加载到了内存中,那么我刚才根据ID获取的Reckoning对象又被加载到内存中了,此时,又多了一个ID与我之前加载Reckoning对象相同的对象,那么我在执行更新操作的时候就报了以上错误扎到了错误的根源一切都好办。使用懒加载就解决了。

<set name="reckonings" table="ITEM_RECKONING" inverse="true" lazy="true">//这里懒加载改为true,问题解决。
            <key>
                <column name="I_ID"></column>
            </key>
            <many-to-many class="com.pms.entities.treatmentManage.Reckoning" column="R_ID"></many-to-many>
        </set>
原文地址:https://www.cnblogs.com/GooPolaris/p/7920454.html