使用hibernate2的时候出现session中对象重复错误

来源:互联网 发布:javascript启示录 pdf 编辑:程序博客网 时间:2024/06/16 05:17

a different object with the same identifier value was already associated with the session

这个已经是hibernate的经典错误啦..

 

hibernate3.0之后版本里,这个错误很好解决,session.merge(object)就可以了..

 

但是我用的却是老掉牙的hibernate2,

没有merge方法,所以只能用别的办法来解决了.

 

代码里.有两个数据实体,

1.工具(Tool),配置文件中:inverse=true,lazy=true

2 合同(Contract);配置文件中:inverse=false,lazy=true

对应关系为多对多的关系.

 

 

引发错误的相关代码片段如下:

Os4Contract contract = (Os4Contract) session.get(Os4Contract.class,                contractid);        // 总共移除合同的代维工具数量        int removeNum = 0;//      合同原来拥有的"已添加工具数量"        int oldamount = contract.getTools().size();                for (int i = 0; i < tools.size(); i++)        {            tool = (Os4Tool) tools.get(i);            tool.getContracts().remove(contract);            contract.getTools().remove(tool);            /*            1.session.update(tool);            1.session.saveOrUpdate(tool);            2.session.evict(tool);            2.session.update(tool);            3.session.clear();//Found two representations of same collection            3.session.update(tool);            4.session.refresh(tool);            4.session.update(tool);            */

 

其中,1,2,4 方法都试过,在update的时候就会提示a different object with the same identifier value was already associated with the session

第3个方法则是Found two representations of same collection 错误.

 

 

上面代码的意图是,将工具从合同中移除, 也就是把工具和合同的映射关系表相关记录给删除掉即可.

因为工具的配置文件中,inverse=true, 也就是说.这个关系映射表由合同来管理,

也就是说,如果要解除contract与tool之间的关系,保存tool是不能达到效果的,

必须保存contract,然后contract才会去维护关系映射表,

所以,就把session.update(tool);这句去掉了.而且这里tool没有做修改,完全没必要update一次,浪费性能.

呵呵,至此,感觉这个问题我其实并没有解决..我只是"避免"了而已..

 

如果真的有个场景,非要update的话.也只能"用一种蠢方法,先删后加,并且放到两个事务中了"