2010-10-04 38 views
24

Tôi đang sử dụng thanh chống và ngủ đông. Tôi có một mối quan hệ cha mẹ và con bằng cách sử dụng thiết lập trong hbm. Trong hành động tôi đang sử dụng phương thức session.saveOrUpdate() để lưu nhưng trong khi lưu, nó sẽ hiển thị lỗi dưới đây. Bất cứ ai có thể giúp đỡ về điều này với lời giải thích, nơi tôi đã làm sai?org.hibernate.StaleStateException: Cập nhật hàng loạt trả về số hàng không mong đợi từ bản cập nhật [0]; số hàng thực tế: 0; dự kiến: 1

Đây là hbm.file tôi

<?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> 

hành động của tôi

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

} 

mô hình mẹ tôi

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; 
} 


} 

mô hình Con tôi

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; 
} 


} 

Và hình thức của tôi

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 = ""; 

} 

} 

Lỗi:

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) 

Trả lời

1

Dường như, cargo có thể có một hoặc nhiều item. Mỗi mục sẽ có tham chiếu đến cargo tương ứng của nó.

Từ nhật ký, item đối tượng là chèn đầu tiên và sau đó là một nỗ lực được thực hiện để cập nhật đối tượng cargo (mà không tồn tại).

Tôi đoán những gì bạn thực sự muốn là cargo đối tượng được tạo ra đầu tiên và sau đó là đối tượng item được tạo ra với các id của đối tượng hàng hóa là tài liệu tham khảo - vì vậy, essentally lại nhìn vào tiết kiệm () trong lớp Hành động.

1

Có vẻ như, khi bạn cố gắng xóa cùng một đối tượng và sau đó lại cập nhật cùng một đối tượng, thì nó sẽ cho bạn lỗi này. Như sau mỗi cập nhật hibernate để kiểm tra an toàn cháy bao nhiêu hàng đã được cập nhật, nhưng trong đoạn mã dữ liệu phải đã bị xóa. Ở đây hibernate phân biệt giữa các đối tượng dựa trên khóa mà u đã gán hoặc phương thức equals.

vì vậy, chỉ cần thực hiện một lần thông qua mã của bạn cho séc này hoặc thử thực hiện bằng phương thức hashcode & chính xác có thể hữu ích.

44

Trong tệp ánh xạ Hibernate cho thuộc tính id, nếu bạn sử dụng bất kỳ lớp trình tạo nào, cho thuộc tính đó, bạn không nên đặt giá trị một cách rõ ràng bằng cách sử dụng phương thức setter.

Nếu bạn đặt giá trị của thuộc tính Id một cách rõ ràng, nó sẽ dẫn đến lỗi ở trên. Kiểm tra điều này để tránh lỗi này.

+0

đầu tiên trong tập tin userCredentials.hbm.xml tôi đã sử dụng Sau khi viết dưới đây một trong những vấn đề được giải quyết. pudaykiran

+0

Điều này đã giải quyết vấn đề tương tự của tôi .. cảm ơn –

+0

Cảm ơn nó hoạt động :) – Prashant

1
/* 
* 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> này sẽ hiển thị cho bạn những SQL được thực thi và gây ra vấn đề.

* StaleStateException sẽ chỉ được ném sau khi chúng tôi xóa thành công một đối tượng, và sau đó cố gắng xóa một đối tượng khác. Lý do cho điều này là, trong khi vẫn duy trì các đối tượng trong các phiên, các đối tượng trước tiên phải bị xóa khỏi Phiên trước khi xóa. Nếu không, các lần xóa tiếp theo sẽ khiến cho số StaleStateException bị ném.

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

* Vấn đề là bảng chỉ có một trường là khóa chính (tôi có khóa tổng hợp và đây không phải là ý tưởng hay, ngoại trừ quan hệ nhiều đến nhiều). Tôi đã giải quyết bằng cách sử dụng một trường bảng id mới tự động gia tăng.

* Có thể khắc phục bằng cách sử dụng Hibernate session.update() - bạn cần có khóa chính của bảng/chế độ xem bằng thuộc tính bean tương ứng của bạn (ví dụ: id).

*

+1

Đây là câu trả lời kém bằng văn bản, bạn có thể thử và rõ ràng hơn một chút không? – Dutts

13

nó xảy ra khi bạn cố gắng xóa cùng một đối tượng và sau đó một lần nữa cập nhật cùng một đối tượng sử dụng này sau khi xóa

session.clear(); 
3

những gì tôi đã trải qua là tăng ngoại lệ này khi cập nhật đối tượng có một id không tồn tại trong bảng. nếu bạn đọc thông báo ngoại lệ, thông báo "Cập nhật hàng loạt đã trả về số hàng không mong đợi từ bản cập nhật [0]; số hàng thực tế: 0; dự kiến: 1" có nghĩa là không thể tìm thấy bản ghi với id đã cho của bạn.

Để tránh điều này tôi luôn đọc bản ghi với cùng id nếu tôi tìm thấy hồ sơ trở lại sau đó tôi gọi cập nhật nếu không ném "ngoại lệ hồ sơ không tìm thấy".

0

Tôi cũng giống như vậy. Làm cho Id (0) đang làm "(giá trị Model của bạn) .setId (0)" đã giải quyết được sự cố của tôi.

-2

nếu id đã cho không tồn tại trong DB, bạn có thể nhận ngoại lệ này.

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 
0

Điều này thường xảy ra khi SQL của bạn xấu (chuyển đổi loại tiềm ẩn, v.v.).

Bật chế độ ngủ đông SQL logging bằng cách thêm các dòng sau vào tính log4j bạn file:

ghi lại câu lệnh SQL

log4j.logger.org.hibernate.SQL = debug

Logs thông số JDBC được chuyển đến truy vấn

log4j.logger.org.hibernate.type = trace

Trước khi thất bại, bạn sẽ thấy câu lệnh SQL cuối cùng được thử trong nhật ký của bạn, sao chép và dán SQL này vào một máy khách SQL bên ngoài và chạy nó.

+0

Bạn nên kiểm tra [answer] để được tư vấn tốt về cách trình bày câu trả lời của bạn tốt hơn. – HiDeo

1

Đối với các phương thức update()saveOrUpdate(), giá trị máy phát điện id phải có trong cơ sở dữ liệu. Đối với phương pháp save(), máy phát điện id không bắt buộc.

0

xin vui lòng không đặt id của lớp con là lớp máy phát điện là nước ngoài chỉ đặt id lớp cha nếu id lớp cha của bạn được chỉ định ... chỉ cần làm một điều không thiết lập id của lớp con thông qua phương pháp setter vấn đề của bạn sẽ được sửa chữa ..... chắc chắn.

+1

Bạn có thể muốn thêm dấu chấm câu, câu trả lời của bạn hiện tại rất khó đọc. – mkl

0

Vì vậy, đối với trường hợp của tôi, tôi nhận thấy hibernate đang cố gắng cập nhật bản ghi thay vì chèn nó và đã ném ngoại lệ được đề cập.

cuối cùng tôi đã phát hiện ra rằng thực thể của tôi đã có một dấu thời gian cột updatedAt:

<timestamp name="updatedDate" column="updated_date" /> 

và khi tôi đã cố gắng để khởi tạo đối tượng tôi thấy rằng mã là thiết lĩnh vực này một cách rõ ràng.

sau khi xóa setUpdateDate (ngày mới()) nó hoạt động và đã chèn thay thế.

0

Như đã đề cập ở trên, hãy đảm bảo rằng bạn không đặt bất kỳ trường id nào được cho là tự động tạo.

Để gây ra sự cố này trong quá trình thử nghiệm, hãy đảm bảo rằng db 'thấy' còn được gọi là SQL này, nếu không mọi thứ có vẻ ổn khi thực sự không.

tôi gặp phải vấn đề này khi chèn mẹ tôi với một đứa trẻ vào db:

  1. Chèn mẹ (với ID bằng tay)
  2. Chèn trẻ em (với ID autogenerated)
  3. Cập nhật khóa ngoại trong Child bảng cho phụ huynh.

Câu lệnh 3. không thành công. Thật vậy, mục nhập với ID được tạo tự động (bằng Hibernate) không có trong bảng khi trình kích hoạt thay đổi ID khi chèn mỗi lần, do đó cho phép cập nhật không thành công mà không tìm thấy hàng phù hợp.

Vì bảng có thể được cập nhật mà không có bất kỳ Hibernate nào tôi đã thêm một kiểm tra xem ID có bị vô hiệu không và chỉ điền vào trong đó để kích hoạt.

Các vấn đề liên quan