错误信息:a different object with the same identifier value was already associated with the session......
字面意思:在session中存在标识符(identifier)相同,对象却不止一个的情况报出异常。
在网上找资料,这是使用hibernate的一个比较常见的异常,原因在于如果在同方法中多次获取同一标识符的对象,并进行update()或者saveOrUpdate()操作的话,在其后获取的对象进行更新操作就会出现这个异常。
示例:
public void saveXX(){
Integer id = x;
Test test = testDao.getById(id);
if(xx){
Test anotherTest = testDao.getById(id);
anotherTest.setName("xyz");
testDao.update(anotherTest);
}
test.setSex("xy");
testDao.update(test);//这行出现问题
}
如果是需要对同一对象进行处理的话,尽量还是不要这样多次获取对象分别取进行更新操作。
解决办法:
1、去掉多次获取的同一标志的对象;
2、使用hibernate的merge方法也替换update方法也可以;