我有一个Java类ClassA,该类定义了休眠映射。在代码中的某个地方,我需要检索保存在数据库中的此类的所有实例:
public List<ClassA> getAllClassA(){
Criteria crit = getSession().createCriteria(ClassA.class);
return crit.list();
}
allA = getAllClassA();
稍后我将删除一些对象,同时更新其他对象:
public void removeItem() {
Iterator<ClassA> it = allA.iterator();
while(it.hasNext()){
ClassA cA = it.next();
if(cA.hasCondition()){
dao.remove(cA);
it.remove();
}
else {
cA.update();
}
}
dao.update(allA);
}
//this is in another class
public void update(List<ClassA> allA){ //dao.update
for(ClassA cA: allA){
getSession().saveOrUpdate(cA);
}
}
发生的情况是数据库已正确更新(并删除了所需的对象),但它还会吐出以下错误:
错误org.hibernate.event.def.AbstractFlushingEventListener.performExecutions:324-无法将数据库状态与会话org.hibernate.StaleStateException同步:批处理更新从更新[0]返回了意外的行数;实际行数:0;预期:1
我知道关于堆栈溢出还有其他类似的问题,但是它们似乎是由不同的情况引起的,在这种情况下没有用。
有任何想法吗?
我不确定为什么,但是如果在更新后执行删除,问题就消失了:
public void removeItem() {
Iterator<ClassA> it = allA.iterator();
ClassA toRemove = null;
while(it.hasNext()){
ClassA cA = it.next();
if(cA.hasCondition()){
toRemove = cA;
it.remove();
}
else {
cA.update();
}
}
dao.update(allA);
if(toRemove!=null)dao.remove(toRemove);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句