org.hibernate.StaleStateException:批量更新从更新 [0] 返回了意外的行数;实际行数:0;预期:1
Posted
技术标签:
【中文标题】org.hibernate.StaleStateException:批量更新从更新 [0] 返回了意外的行数;实际行数:0;预期:1【英文标题】:org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1 【发布时间】:2011-04-20 16:00:48 【问题描述】:我正在使用struts 和hibernate。我在 hbm 中有一个使用 set 的父子关系。
在操作中,我使用session.saveOrUpdate()
方法进行保存,但在保存时显示以下错误。谁能帮忙解释一下我在哪里犯了错误?
这是我的 hbm.file
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.model.cargo" table="cargo">
<id name="id" column="id" type="java.lang.Long">
<generator class="increment" />
</id>
<property name="cname" column="cname" />
<property name="cdate" column="cdate" />
<property name="csource" column="csource" />
<property name="cdestination" column="cdestination" />
<property name="create" column="createby" />
<property name="status" column="status" />
<set name="itemList" table="item" inverse="true"
cascade="all-delete-orphan">
<key>
<column name="id" />
</key>
<one-to-many class="com.model.Item" />
</set>
</class>
<class name="com.model.Item" table="item">
<id name="itemid" column="itemid" type="java.lang.Long">
<generator class="increment" />
</id>
<property name="itemName" column="itemname" />
<property name="weight" column="weight" />
<many-to-one class="com.model.cargo" name="cargo"
column="id" />
</class>
</hibernate-mapping>
我的行动
package com.action;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.plugin.HibernatePlugIn;
import com.form.cargoForm;
import com.model.cargo;
import com.model.Item;
public class CargoAction extends DispatchAction
public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
if (log.isDebugEnabled())
log.debug("Entering Master add method");
try
cargoForm cargoForm = (cargoForm) form;
//System.out.println("ID" + cargoForm.getId());
cargo cargo = new cargo();
System.out.println("in cargo Action");
// copy customerform to model
cargoForm.reset(mapping, request);
BeanUtils.copyProperties(cargo, cargoForm);
cargoForm.reset(mapping, request);
// cargoForm.setInputParam("new");
// updateFormBean(mapping, request, cargoForm);
catch (Exception ex)
ex.printStackTrace();
return mapping.findForward("failure");
return mapping.findForward("success1");
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
SessionFactory sessionFactory=null;
Session session =null;
System.out.println("in cargo Action");
try
sessionFactory = (SessionFactory) servlet
.getServletContext().getAttribute(HibernatePlugIn.KEY_NAME);
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
cargoForm carForm = (cargoForm) form;
cargo cargo = new cargo();
System.out.println("in cargo Action");
BeanUtils.copyProperties(cargo,carForm);
System.out.println("id"+ carForm.getId());
System.out.println("item id"+ carForm.getItemid());
Set itemset = carForm.getItemDtl();
System.out.println("size"+itemset.size());
Iterator iterator =itemset.iterator();
while(iterator.hasNext())
Item it = (Item)iterator.next();
System.out.println("name"+it.getItemName()); //log.debug("HERE");
it.setCargo(cargo);
cargo.setItemList(itemset);
System.out.println("size"+ itemset.size());
session.saveOrUpdate("cargo",cargo);
tx.commit();
catch(Exception e)
e.printStackTrace();
return mapping.findForward("success");
public ActionForward search(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
System.out.println("in cargo search Action");
SessionFactory sessionFactory = (SessionFactory) servlet
.getServletContext().getAttribute(HibernatePlugIn.KEY_NAME);
HttpSession session1 = request.getSession();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
cargoForm cargoform = (cargoForm) form;
// System.out.println("Name"+cargoForm.getName());
cargo cargo = new cargo();
System.out.println("in cargo search Action");
// copy customerform to model
BeanUtils.copyProperties(cargo, cargoform);
String name;
String status;
String createby;
name = cargo.getCname();
status = cargo.getStatus();
createby = cargo.getCreate();
System.out.println("Name..." + name);
System.out.println("status..." + status);
System.out.println("createby..." + createby);
try
if ((name.equals("")) && (createby.equals(""))
&& (status.equals("")))
return mapping.findForward("failure");
String SQL_QUERY = "from cargo c where c.cname=:name or c.status=:status or c.create=:createby";
Query query = session.createQuery(SQL_QUERY);
query.setParameter("name", name);
query.setParameter("status", status);
query.setParameter("createby", createby);
ArrayList al = new ArrayList();
for (Iterator i = query.iterate(); i.hasNext();)
cargo cargo1 = (cargo) i.next();
al.add(cargo1);
System.out.println("Cargo ID is:" + cargo1.getId());
System.out.println("Cargo list is:" + al.size());
session1.setAttribute("clist", al);
catch (Exception e)
e.printStackTrace();
return mapping.findForward("failure");
System.out.println("search Cargo list is success");
return mapping.findForward("success");
public ActionForward edit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
SessionFactory sessionFactory=null;
Session session =null;
if (log.isDebugEnabled())
log.debug("Entering Master Edit method");
try
sessionFactory = (SessionFactory) servlet
.getServletContext().getAttribute(HibernatePlugIn.KEY_NAME);
session = sessionFactory.openSession();
Transaction transaction=session.beginTransaction();
cargoForm carForm = (cargoForm) form;
// System.out.println(carForm.getStatus());
// System.out.println(carForm.getCreate());
cargo cargo = new cargo();
BeanUtils.copyProperties(cargo, carForm);
System.out.println("In Cargo Edit "+cargo.getId());
String qstring = "from cargo c where c.id=:id";
Query query = session.createQuery(qstring);
query.setParameter("id", cargo.getId());
ArrayList all = new ArrayList();
cargo c = (cargo) query.iterate().next();
System.out.println("Edit Cargo list " + all.size());
Set purchaseArray = new HashSet();
System.out.println("Edit"+c.getItemList().size());
carForm.setItemDtl(purchaseArray);
BeanUtils.copyProperties(carForm,c);
// transaction.commit();
session.flush();
catch (Exception e)
e.printStackTrace();
return mapping.findForward("failure");
// return a forward to edit forward
System.out.println("Edit Cargo list is success");
return mapping.findForward("succ");
public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
try
SessionFactory sessionFactory = (SessionFactory) servlet
.getServletContext().getAttribute(HibernatePlugIn.KEY_NAME);
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
cargoForm carForm = (cargoForm) form;
// System.out.println(carForm.getStatus());
// System.out.println(carForm.getCreate());
cargo cargo = new cargo();
BeanUtils.copyProperties(cargo, carForm);
System.out.println("In Cargo Delete "+cargo.getId());
//String qstring = "delete from cargo c where c.id=:id";
//Query query = session.createQuery(qstring);
session.delete("cargo",cargo);
// session.delete(cargo);
// session.flush();
//query.setParameter("id", cargo.getId());
//int row=query.executeUpdate();
//System.out.println("deleted row"+row);
tx.commit();
catch (Exception e)
e.printStackTrace();
return mapping.findForward("failure");
// return a forward to edit forward
System.out.println("Deleted success");
return mapping.findForward("succes");
我的父模型
package com.model;
import java.util.HashSet;
import java.util.Set;
public class cargo
private Long id;
private String cname;
private String cdate;
private String csource;
private String cdestination;
private String create;
private String status;
private Set itemList = new HashSet();
public Long getId()
return id;
public void setId(Long id)
this.id = id;
public String getCname()
return cname;
public void setCname(String cname)
this.cname = cname;
public String getCdate()
return cdate;
public void setCdate(String cdate)
this.cdate = cdate;
public String getCsource()
return csource;
public void setCsource(String csource)
this.csource = csource;
public String getCdestination()
return cdestination;
public void setCdestination(String cdestination)
this.cdestination = cdestination;
public String getCreate()
return create;
public void setCreate(String create)
this.create = create;
public String getStatus()
return status;
public void setStatus(String status)
this.status = status;
public Set getItemList()
return itemList;
public void setItemList(Set itemList)
this.itemList = itemList;
我的孩子模型
package com.model;
public class Item
private Long itemid;
private String itemName;
private String weight;
private cargo cargo;
public Long getItemid()
return itemid;
public void setItemid(Long itemid)
this.itemid = itemid;
public String getItemName()
return itemName;
public void setItemName(String itemName)
this.itemName = itemName;
public String getWeight()
return weight;
public void setWeight(String weight)
this.weight = weight;
public cargo getCargo()
return cargo;
public void setCargo(cargo cargo)
this.cargo = cargo;
还有我的表格
package com.form;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import com.model.Item;
public class cargoForm extends ActionForm
private Long id;
private String cname;
private String cdate;
private String csource;
private String cdestination;
private String create;
private String status;
private Long[] itemid;
private String[] itemName;
private String[] weight;
private Set itemset = new HashSet();
public Long getId()
return id;
public void setId(Long id)
this.id = id;
public String getCname()
return cname;
public void setCname(String cname)
this.cname = cname;
public String getCdate()
return cdate;
public void setCdate(String cdate)
this.cdate = cdate;
public String getCsource()
return csource;
public void setCsource(String csource)
this.csource = csource;
public String getCdestination()
return cdestination;
public void setCdestination(String cdestination)
this.cdestination = cdestination;
public String getCreate()
return create;
public void setCreate(String create)
this.create = create;
public String getStatus()
return status;
public void setStatus(String status)
this.status = status;
public Long[] getItemid()
return itemid;
public void setItemid(Long[] itemid)
this.itemid = itemid;
public String[] getItemName()
return itemName;
public void setItemName(String[] itemName)
this.itemName = itemName;
public String[] getWeight()
return weight;
public void setWeight(String[] weight)
this.weight = weight;
/*
* public Set getItemset() return itemset;
*
* public void setItemset(Set itemset) this.itemset = itemset;
*/
public Set getItemDtl()
if (itemid != null)
itemset = new HashSet();
System.out.println("cargadd form" + itemid);
for (int i = 0; i < itemid.length; i++)
Item it = new Item();
// it.setItemId(itemId[i]);
it.setItemName(itemName[i]);
System.out.println("cargadd form" + itemName[i]);
it.setWeight(weight[i]);
itemset.add(it);
System.out.println("cargadd form" + itemset.size());
return itemset;
public void setItemDtl(Set itemset)
System.out.println("cargadd form" + itemset.size());
this.itemset = itemset;
System.out.println("cargadd form" + itemset.size());
public void reset(ActionMapping mapping, HttpServletRequest request)
cname = "";
csource = "";
cdestination = "";
cdate = "";
status = "";
create = "";
错误:
Hibernate: select max(itemid) from item
Hibernate: insert into item (itemname, weight, position, id, itemid) values (?, ?, ?, ?, ?)
Hibernate: update cargo set name=?, date=?, source=?, destination=?, createby=?, status=? where id=?
Oct 4, 2010 10:44:08 AM org.hibernate.jdbc.BatchingBatcher doExecuteBatch
SEVERE: Exception executing batch:
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:140)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.action.CargoAction.save(CargoAction.java:125)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Unknown Source)
Oct 4, 2010 10:44:08 AM org.hibernate.event.def.AbstractFlushingEventListener performExecutions
SEVERE: Could not synchronize database state with session
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:140)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.action.CargoAction.save(CargoAction.java:125)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Unknown Source)
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:140)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.action.CargoAction.save(CargoAction.java:125)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Unknown Source)
【问题讨论】:
【参考方案1】:在 id
属性的 Hibernate 映射文件中,如果您使用任何生成器类,则不应使用 setter 方法显式设置该属性的值。
如果显式设置Id属性的值,会导致上面的错误。选中此项以避免此错误。
【讨论】:
首先在 userCredentials.hbm.xml 文件中我使用了当您尝试删除同一个对象然后再次更新同一个对象时会发生这种情况 删除后使用这个
session.clear();
【讨论】:
【参考方案3】:我所经历的是,更新对象时会引发此异常,该对象的 id 不存在于表中。如果您阅读异常消息,它会显示“批量更新从更新 [0] 返回了意外的行数;实际行数:0;预期:1”,这意味着它无法找到具有您给定 ID 的记录。
为了避免这种情况,如果我找到记录,我总是读取具有相同 id 的记录,然后我调用更新,否则抛出“找不到异常记录”。
【讨论】:
【参考方案4】:看起来,cargo
可以有一个或多个 item
。每个项目都会引用其对应的cargo
。
从日志中,item
对象首先被插入,然后尝试更新cargo
对象(不存在)。
我猜你真正想要的是首先创建 cargo
对象,然后以货物对象的 id 作为参考创建 item
对象 - 所以,基本上是- 查看Action类中的save()方法。
【讨论】:
【参考方案5】:看起来,当您尝试删除同一个对象然后再次更新同一个对象时,它会给您这个错误。每次更新休眠以进行安全检查后,都会触发更新了多少行,但是在代码期间必须删除数据。在这里,hibernate 根据您分配的键或 equals 方法区分对象。
所以,只需通过您的代码进行一次检查,或者尝试正确实现 equals 和 hashcode 方法,这可能会有所帮助。
【讨论】:
【参考方案6】:/*
* Thrown when a version number or timestamp check failed, indicating that the
* Session contained stale data (when using long transactions with versioning).
* Also occurs if we try delete or update a row that does not exist.
*
*/
if ( expectedRowCount > rowCount )
throw new StaleStateException(
"Batch update returned unexpected row count from update [" + batchPosition +"]; actual row count: " + rowCount +"; expected: " + expectedRowCount);
<property name="show_sql">true</property>
这应该向您显示执行并导致问题的 SQL。
*只有在我们成功删除一个对象,然后尝试删除另一个对象后,才会抛出 StaleStateException。这样做的原因是,在跨会话持久化对象时,必须先从会话中删除对象,然后才能删除。否则,后续删除将导致StaleStateException
被抛出。
Session.Remove(obj);
objectDAO.Delete(obj);
*问题是一个表必须只有一个字段是主键(我有一个复合键,这不是一个好主意,除了多对多关系)。我已经解决了使用自动增量的新 id 表字段。
*它可以通过使用Hibernate session.update()
来修复——你需要让表/视图的主键等于你相应的 bean 属性(例如 id)。
*
【讨论】:
这是一个写得很糟糕的答案,你能试着说清楚一点吗?【参考方案7】:对于update()
和saveOrUpdate()
方法,id
生成器值应该存在于数据库中。对于save()
方法,不需要id
生成器。
【讨论】:
【参考方案8】:如上所述,请确保您没有设置任何应该自动生成的 id 字段。
要在测试期间导致此问题,请确保数据库“看到”也就是刷新此 SQL,否则一切看起来都很好,但实际上并非如此。
将我的父母和孩子插入数据库时遇到了这个问题:
-
插入父项(使用手动 ID)
插入子项(使用自动生成的 ID)
将子表中的外键更新为父表。
3. 语句失败。实际上,具有自动生成 ID(由 Hibernate 生成)的条目不在表中,因为触发器在每次插入时都会更改 ID,从而导致更新失败,找不到匹配的行。
由于无需任何 Hibernate 即可更新表,因此我添加了一个检查 ID 是否为空,然后仅将其填充到触发器中。
【讨论】:
谢谢!我一直在努力解决这个问题,并查看您的答案,我找到了解决方案。我有一个总是设置新标识符的触发器。替换了触发代码,以便仅在插入之前没有标识符时才设置新标识符。现在可以使用了。【参考方案9】:当 SQL 语句以某种性能成本高的方式(隐式类型转换等)实现时,通常会发生这种情况。
我建议调试生成的 SQL 语句。
调试开启 SQL 日志记录
通过将以下行添加到您的 log4j 属性文件来打开休眠 SQL 日志记录:
# logs the SQL statements
log4j.logger.org.hibernate.SQL=debug
# Logs the JDBC parameters passed to a query
log4j.logger.org.hibernate.type=trace
在失败之前,您将在日志中看到最后尝试的 SQL 语句,将这条 SQL 复制并粘贴到外部 SQL 客户端并运行它。
【讨论】:
您应该查看How to Answer 以获得有关如何更好地呈现您的答案的好建议。【参考方案10】:我也有同样的情况。使 Id (0) 执行“(您的模型值).setId(0)”解决了我的问题。
【讨论】:
【参考方案11】:请不要设置子类的 id,它是生成器类是外来的,只有在分配了父类 id 时才设置父类 id... 只需做一件事,不要通过 setter 方法设置子类的 id,您的问题将得到解决.....肯定。
【讨论】:
您可能想添加标点符号,您的答案目前很难阅读。【参考方案12】:所以对于我来说,我注意到 hibernate 正在尝试更新记录而不是插入它,这引发了提到的异常。
我终于发现我的实体有一个 updatedAt 时间戳列:
<timestamp name="updatedDate" column="updated_date" />
当我尝试初始化对象时,我发现代码是 明确设置此字段。
在删除 setUpdateDate(new Date()) 之后,它工作并执行了插入操作。
【讨论】:
【参考方案13】:仅供参考,发生此异常的另一种方式是:
你的事务隔离是READ_COMMITTED
事务 #1 查询实体,然后删除该实体
同时交易 #2 做同样的事情
然后可能会发生这种情况:TX #1 在 TX #2 之前成功提交,然后当 TX #2 尝试(再次)删除实体时,它不再存在 - 即使它是在同一事务中的较早查询中找到的.请注意,READ_COMMITTED
隔离允许此异常。
在我的情况下,生成的异常如下所示:
HHH000315: Exception executing batch [org.hibernate.StaleStateException:
Batch update returned unexpected row count from update [0]; actual row
count: 0; expected: 1; statement executed: delete from Foobar where id=?],
SQL: delete from Foobar where id=?
【讨论】:
【参考方案14】:如果给定的 id 在数据库中不存在,那么你可能会得到这个异常。
Exception in thread "main" org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
【讨论】:
以上是关于org.hibernate.StaleStateException:批量更新从更新 [0] 返回了意外的行数;实际行数:0;预期:1的主要内容,如果未能解决你的问题,请参考以下文章