org.hibernate.StaleStateException:批量更新从更新 [0] 返回了意外的行数;实际行数:0;预期的

Posted

技术标签:

【中文标题】org.hibernate.StaleStateException:批量更新从更新 [0] 返回了意外的行数;实际行数:0;预期的【英文标题】:org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected 【发布时间】:2014-03-04 16:56:49 【问题描述】:

当我尝试从我的 spring mvc 应用程序更新数据库中的值时出现此错误:

 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 org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:656)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
        at com.sun.proxy.$Proxy21.updatePerson(Unknown Source)
        at se.lowdin.civilforsvaret.webapp.controller.EditPersonContoller.save(EditPersonContoller.java:57)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:601)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:722)
    DEBUG: org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
    TRACE: org.hibernate.jdbc.AbstractBatcher - closing statement
    ERROR: org.hibernate.event.def.AbstractFlushingEventListener - 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 org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:656)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
        at com.sun.proxy.$Proxy21.updatePerson(Unknown Source)
        at se.lowdin.civilforsvaret.webapp.controller.EditPersonContoller.save(EditPersonContoller.java:57)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:601)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:722)
    TRACE: org.hibernate.jdbc.ConnectionManager - registering flush end
    DEBUG: org.hibernate.transaction.JDBCTransaction - rollback
    DEBUG: org.hibernate.transaction.JDBCTransaction - re-enabling autocommit
    DEBUG: org.hibernate.transaction.JDBCTransaction - rolled back JDBC Connection
    TRACE: org.hibernate.jdbc.JDBCContext - after transaction completion
    DEBUG: org.hibernate.jdbc.ConnectionManager - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!
    TRACE: org.hibernate.impl.SessionImpl - after transaction completion
    TRACE: org.hibernate.impl.SessionImpl - closing session
    TRACE: org.hibernate.jdbc.ConnectionManager - performing cleanup
    DEBUG: org.hibernate.jdbc.ConnectionManager - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
    TRACE: org.hibernate.jdbc.JDBCContext - after transaction completion
    DEBUG: org.hibernate.jdbc.ConnectionManager - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!
    TRACE: org.hibernate.impl.SessionImpl - after transaction completion
    feb 07, 2014 11:04:32 FM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet [spring] in context with path [/CRUDWebAppMavenized] threw exception [Request processing failed; nested exception is 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] with root cause
    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 org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:656)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
        at com.sun.proxy.$Proxy21.updatePerson(Unknown Source)
        at se.lowdin.civilforsvaret.webapp.controller.EditPersonContoller.save(EditPersonContoller.java:57)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:601)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:722)

所以我的实际错误似乎与数据库中的 ID 和正在更新的内容有关。 在我的 GET 方法中,我得到了当前 ID,在本例中为 10。

@Autowired
PersonService service;


@RequestMapping(method = RequestMethod.GET)
public ModelAndView index(@PathVariable int id) 

    EditPersonBean bean = new EditPersonBean();

    if (id > 0) 
        Person person = service.getPerson(id);
        bean.copyValuesToBean(person);
    

    ModelAndView mav = new ModelAndView("editPerson");
    mav.addObject("editPersonBean", bean);
    return mav;


但是在我的 post 方法中,这个 10 的 ID 突然变为 0,我相信这可能是导致此错误的原因?

@RequestMapping(value = "/edit", method = RequestMethod.POST)
        public String save (EditPersonBean bean, Person person, @RequestParam(value = "file", required = false) MultipartFile file) 


            System.out.println("incoming id : " + bean.getId());

            try 

                Blob blob = Hibernate.createBlob(file.getInputStream());
                bean.copyBeanValuesToPerson(person,blob);
                service.updatePerson(person);

             catch (IOException e) 
                e.printStackTrace();
            


            return "redirect:/person.html";
        

那么可能是什么原因造成的,或者是其他错误?

public class EditPersonBean 

        private int id;
        private String firstName;
        private String lastName;
        private String email;
        private String phoneNumber;
        private String otherInfo;
        private Blob image;
        private String userName;
        private String password;

        public void copyValuesToBean(Person person)

            setId((int) person.getId());
            setFirstName(person.getFirstName());
            setLastName(person.getLastName());
            setEmail(person.getEmail());
            setPhoneNumber(person.getPhoneNumber());
            setOtherInfo(person.getOtherInfo());
            setImage(person.getImage());
            setUserName(person.getUserName());
            setPassword(person.getPassword());;

        

@Entity
public class Person 

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private int id;
    @Column(name = "FIRSTNAME")
    private String firstName;
    @Column(name = "SECONDNAME")
    private String lastName;
    @Column(name = "EMAIL")
    private String email;
    @Column(name = "MobilePHONENUM")
    private String phoneNumber;
    @Column(name = "OTHER")
    private String otherInfo;
    @Column(name = "image")
    @Lob
    private Blob image;
    @NotEmpty
    @Size(min = 1, max = 50)
    @Column(name = "username")
    private String userName;
    @NotEmpty
    @Size(min = 1, max = 20)
    @Column(name = "password")
    private String password;

    public Person() 

    

    public Person(int id, String firstName, String lastName, String email,
            String phoneNumber, String otherInfo, Blob image, String userName, String password) 

        setId(id);
        setFirstName(firstName);
        setLastName(lastName);
        setEmail(email);
        setPhoneNumber(phoneNumber);
        setOtherInfo(otherInfo);
        setImage(image);
        setUserName(password);
        setPassword(userName);

     //Getters and setters...

JPA 类:

@Override
    public Person getPerson(int personId) 
        return (Person)session.getCurrentSession().get(Person.class, personId);
    

【问题讨论】:

【参考方案1】:

这个错误通常是由于休眠找不到它需要更新的所有行而引起的。 这意味着当您尝试更新从数据库中提取的某些对象时,它们实际上不再存在(或者从一开始就不存在)。

可能是因为另一个线程正在删除它们,或者数据库的隔离模式设置为 read_uncommited,因此由另一个事务创建的行无法保存(由于事务失败)并且不再存在。

【讨论】:

如果我在读取实体时收到此错误,这意味着什么? 该实体不再存在...创建它的事务已回滚【参考方案2】:

准确知道发生了什么的唯一方法是在您的 Hibernate.cfg.xml 配置中打开 Hibernate 语句日志记录。这是因为堆栈跟踪中的行号都与执行实际 Hibernate 操作的代码部分不对应。相反,这些操作被批处理,然后在事务关闭时(或在指定数量的操作被批处理之后)一次全部执行。

要启用 Hibernate 语句日志记录,

    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <property name="use_sql_comments">true</property>

也就是说,上次我遇到这个问题时,记录被不同线程/事务中的一般 HQL 更新删除,然后当前线程/事务试图按 ID 删除完全相同的记录。不幸的是,由于事务是批处理的,因此您在执行删除操作时看不到它,而是在程序执行后期的某个时间点看到它。因此需要打开语句日志来查看哪个实际的 Hibernate 操作触发了异常。

【讨论】:

我发现,我以错误的方式使用了EntityManager,发出了insert,而不是update。谢谢【参考方案3】:

我在我的 Spring Boot 应用程序中也遇到了这个问题。我的情况如下: 使用@Transaction 注释的外部方法。在这里面,我有两种不同的方法: 方法 1 是删除也有@Transaction 的记录。 方法 2 是读取相同的记录,也使用 @Transaction 进行注释。 这里出现问题是因为默认情况下@Transaction 注释支持使用当前事务的 Propagation.REQUIRED。因此,在方法 2 中,当我尝试读取数据时,显然会出现 Stale 异常。 对我有用的修复是我用注释方法 1 @Transactional(propagation = Propagation.REQUIRES_NEW)

所以方法 2 总是使用一个不会有 Stale 数据的单独事务。

【讨论】:

【参考方案4】:

我遇到了类似的问题,我试图保存一个对象,其中他的 id 是原始字段(长),并且在创建对象时,id 默认设置为 0,Hibernate 假设我想要更新 id = 0 的行(显然不存在)。

我的解决方案是将 id 字段更改为 Long(包装器),这样,当我创建一个新实例时,id 设置为 null,Hibernate 知道我正在向数据库中插入一个新元素。 我希望它有所帮助。谢谢。

【讨论】:

【参考方案5】:

首先检查对象的变量,即映射到休眠状态的 Id(使用生成器类)是否不包含任何陈旧值。

如果记录被任何其他线程或操作删除,但您的 Id 变量仍包含陈旧值,并且当您更新数据库中的记录时,它会给您此异常,因为将没有记录数据库中的给定 ID,因此您必须保存对象而不是更新,因为首先没有更新记录的范围

否则

在使用 saveOrUpdate 方法时将 id 设置为 null。

【讨论】:

【参考方案6】:

我遇到了类似的问题,当我添加 cascade='save-update' 时,它解决了我的问题。

这是我对 CF 应用程序的修复。

【讨论】:

CF...云代工?加拿大军队?【参考方案7】:

我收到此错误是因为我想更新数据并且我使用了

service.update(user);

但是出于测试目的,我清除了 用户表,忘记将方法更改为

service.saveOrUpdate(user);

于是我改了,问题就解决了。

【讨论】:

【参考方案8】:

100% 解决方案: 1 确保表中的 id 是自动递增的 你所有的外键都不为空 范围是会话

【讨论】:

【参考方案9】:

只需在您的休眠查询中输入save 而不是saveOrUpdate。这是由于以前的日志,您的班级正在生成一些其他 ID,这些 ID 以前存储在您的表中。因此,hibernate 尝试使用相同的 ID 进行更新,但找不到具有该 ID 的行,因此它给出了 staleStateException

【讨论】:

【参考方案10】:

有些时候我们使用生成器类来生成一行的主键......但是我们在程序中强制添加它,我们会得到 stalestateException。

student=new Student();
       student.setId(4);
       student.setName("thatha");
       student.setDept("dev");

           try 
               transaction = session.beginTransaction();

               session.save(student);
               transaction.commit();
               System.out.println("student is updated");

            catch (HibernateException e) 
               e.printStackTrace();
               transaction.rollback();
               System.out.println("tx is rollback");
           

【讨论】:

【参考方案11】:

在父实体类中指定以下注释属性:-

import javax.persistence.CascadeType           
import javax.persistence.FetchType

@OneToMany(targetEntity = PhoneNumber.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)

【讨论】:

【参考方案12】:

当您使用 spring-data-jpa 将数据持久保存在已启用分区的表中时,可能会发生此异常。

在这种情况下,如果你使用 crudrepository 的保存方法,你会得到这个异常。原因是,在后台,spring JPA 使用休眠来触发 sql 查询。如果您正在插入数据,则会发生此错误,因为插入语句返回“0行插入”作为插入语句执行的响应(仅在启用分区时)。 Hibernate 期望返回 1,因为它没有得到它,所以它回滚插入的行。

如果您遇到此类错误,我建议您连接到数据库并从控制台手动触发 sql 查询并检查响应。您应该能够进一步调查您的问题。

您可以在 spring/java/hibernate 项目中实现的另一种解决方法是使用实​​体管理器来触发本机 sql 查询。

【讨论】:

【参考方案13】:

添加级联进行更新。如果涉及外键将解决问题。

【讨论】:

【参考方案14】:

如果表中的主键被提及为自动递增并且您强制显式提供值,它将引发陈旧状态异常。

【讨论】:

【参考方案15】:

这个异常主要发生在我们在hibernate中执行UPDATE操作的时候。如果我们提到 ID 作为 PRIMARY KEY & AUTO_INCREMENT 并且我们使用另一个 id 来更新数据往往会导致异常...PRIMARY KEY 必须相同

在执行更新操作时使用简单的外行语言 ID将相同 其余数据可以更改 ................................... 或者如果您愿意,可以使用级联属性来更改 ID

【讨论】:

【参考方案16】:

如果是 @Entity 的删除操作:检​​查您没有将 JPA 绑定(@..to..)复制到相同的相关记录。 在这种情况下,JPA 实现可以尝试两次删除相同的引用记录。我使用 Hibernate+SpringData 遇到了这个问题。

【讨论】:

以上是关于org.hibernate.StaleStateException:批量更新从更新 [0] 返回了意外的行数;实际行数:0;预期的的主要内容,如果未能解决你的问题,请参考以下文章