出现 org.hibernate.NonUniqueObjectException 错误的解决方法

    技术2022-05-11  85

     org.hibernate.NonUniqueObjectException:a different object with the same identifier value was already associated with the session

    解释:在session中具有相同标识符的不同对象已经关联。在同一个session中关联了两个同ID的实体对象。

    session里对一个Class不允许用两个ID相同,但是不相等(==)的Object这个在Open Session In view中很容易发生。有的说是session没有及时关闭的导致的。

    在网上狂搜一通,总结的解决办法如下:

    1.一个通常可用但是并不稳妥的办法:

                 Session.flush() before save(or update)

               session.evict(objPO);或者在update之前session.clear();

    2.出现在bidirectional many-to-many中, 把一边的cascade设为none就可以了(两边都设为save-update就会出现这个问题)。 等等

    我一一试过,无效,而且改的东西都是我不想改的

    最后终于解决了

    就是在update或delete时,要把所操作的对象findby出来,就OK了

     主要参考了一下程序,才茅塞顿开

    引用:http://flower-city.spaces.live.com/blog/cns!5CDF3197CFFC015F!123.entry 中的 

    class A{}

    class B{

    private A many_to_one_A;

    }  

    public void update_A_B(A a) {

    B b=findByA(a);

    update(b);

    update(a);

    }

    错误原因:传进来的A是一个独立实体,加载B后,b对象会加载一个a在这个session中,如此在update(a)时,session重新加载并update,如此重复了,

    解决办法:

    public void update_A_B(A a) {

    B b=findByA(a);

    update(b);

    a=b.getMany_to_one_A();

    update(a);

    }

     

    最新回复(0)