用 hibernate 做批量添加操作时,报错:a different object with the same identifier value was already associated with the session 报错。
网上搜到一些,解决方法,如用 session.merge(),用 session.clear() 等,都不管用。
然后又搜到一篇博客,说到的方法管用: https://my.oschina.net/u/3285916/blog/900518
解决方法是: 先用 id 去数据库查有没有这条数据,如果没有,就做 save 操作;
如果有,就设置上其他的实体类属性,然后执行 update 操作。
这样就不报错了。

Hibernate批量添加错误解决方案
本文解决Hibernate批量添加操作中出现的“adifferentobjectwiththesameidentifiervaluewasalreadyassociatedwiththesession”错误。通过先查询数据库判断数据是否存在,再决定进行save或update操作,有效避免了该问题。
2287

被折叠的 条评论
为什么被折叠?



