org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

0 votes
asked Oct 4, 2010 by subbu

I am using struts and hibernate. I have a parent and child relation using set in hbm. In the action I am using session.saveOrUpdate() method to save but while saving it is showing the below error. Can anyone help regardng this with explanation where I made the mistake?

Here is my 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>

My action

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");
  retur

11 Answers

0 votes
answered Jan 4, 2010 by raghuram

It looks like, cargo can have one or more item. Each item would have a reference to its corresponding cargo.

From the log, item object is inserted first and then an attempt is made to update the cargo object (which does not exist).

I guess what you actually want is cargo object to be created first and then the item object to be created with the id of the cargo object as the reference - so, essentally re-look at the save() method in the Action class.

0 votes
answered Jan 4, 2010 by m-j

It looks like, when you try to delete the same object and then again update the same object, then it gives you this error. As after every update hibernate for safe checking fires how many rows were updated, but during the code the data must have been deleted. Over here hibernate distinguish between the objects based on the key what u have assigned or the equals method.

so, just go through once through your code for this check, or try with implementing equals & hashcode method correctly which might help.

0 votes
answered Jan 8, 2013 by srinivasulu-p

In the Hibernate mapping file for the id property, if you use any generator class, for that property you should not set the value explicitly by using a setter method.

If you set the value of the Id property explicitly, it will lead the error above. Check this to avoid this error.

0 votes
answered Jan 17, 2013 by sumit-singh

its happen when you try to delete the same object and then again update the same object use this after delete

session.clear();
0 votes
answered Jan 22, 2013 by joel
/*
* 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> This should show you the SQL that is executed and causes the problem.

*The StaleStateException would be thrown only after we successfully deleted one object, and then tried to delete another. The reason for this is, while persisting the objects across sessions, objects must first be deleted from the Session before deleted. Otherwise, subsequent deletes will cause the StaleStateException to be thrown.

 Session.Remove(obj); 
 objectDAO.Delete(obj);

*The problem was that a table must have only one field that is primary key (I had a composite key and this is not a good idea, except for the many to many relation). I have solved using a new id table field auto incremental.

*It can be fix by using Hibernate session.update() -- you need to have the table/view's primary key equal your corresponding bean property (eg. id).

*

0 votes
answered Jan 22, 2014 by muhammad-suleman

what i have experienced is that this exception raise when updating object have an id which not exist in table. if you read exception message it says "Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1" which means it was unable to found record with your given id.

To avoid this i always read record with same id if i found record back then i call update otherwise throw "exception record not found".

0 votes
answered Jan 2, 2015 by emrah-denizer

I had the same as well.Making the Id (0) doing "(your Model value).setId(0)" solved my problem.

0 votes
answered Jan 7, 2016 by user7260064

For update() and saveOrUpdate() methods, id generator value should be there in the database. For the save() method, id generator is not required.

0 votes
answered Jan 11, 2016 by blanford-robinson

This often happens when your SQL is bad (implicit type conversions etc.).

Turn on hibernate SQL logging by adding the following lines to your log4j properties file:

logs the SQL statements

log4j.logger.org.hibernate.SQL=debug

Logs the JDBC parameters passed to a query

log4j.logger.org.hibernate.type=trace

Before failing you will see the last SQL statement attempted in your log, copy and paste this SQL into an external SQL client and run it.

0 votes
answered Jan 12, 2016 by manjunath

if The given id is not exist in the DB ,then you may get this exception.

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
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...