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

16

27

I am getting this error when I am trying to update values in my database from my spring mvc application :

 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)

So my actual error seem to be something with the ID´s in the database and whats being updated. In my GET method I am getting the current ID which in this case is 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;

}

But in my post method this ID that was 10 is suddenly 0 which I belive might be the cause of this error?

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

What then could be the cause of this or is the error something else?

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 class :

@Override
    public Person getPerson(int personId) {
        return (Person)session.getCurrentSession().get(Person.class, personId);
    }
Karaite answered 7/2, 2014 at 10:20 Comment(0)
K
24

This error usually caused when the hibernate can't find all the rows it needs to update. Meaning that when you try to update some objects that were pulled from the DB they don't really exist anymore (or never existed in the first place).

It might be because another thread is deleting them or that the DB's isolation mode is set to read_uncommited and so rows that were created by another transaction failed to save (due to a transaction failure) and don't exist anymore.

Karleenkarlen answered 11/8, 2014 at 15:1 Comment(2)
What does it mean if i'm getting this error on read of an entity?Airfield
that this entity doesnt exist anymore... the transaction that created it was rollbackedKarleenkarlen
L
13

The only way to exactly know what is happening is to turn on Hibernate statement logging in your Hibernate.cfg.xml configuration. That is because none of the line numbers in the stack trace correspond with the part of your code that performed the actual Hibernate operation. Instead, the operations are batched and then executed all at once upon transaction close (or after a specified number of operations have been batched).

To enable Hibernate statement logging,

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

That said, last time I ran into this issue, it was a case of a record being deleted by general HQL update in a different thread/transaction, then the current thread/transaction trying to delete the exact same record by ID. Unfortunately since the transaction is batched you don't see it at the point you did the delete but, rather, at some point way later in the program execution. Thus the need to turn on statement logging to see which actual Hibernate operation triggered the exception.

Lentz answered 18/3, 2014 at 19:56 Comment(2)
with this I found out, that I used the EntityManager in the wrong way and an insert was issued instead of an update. ThxTiffa
If you're using logback-spring you can cause hibernate to show sql statements via the logback-spring.xml file: <configuration><logger name="org.hibernate.SQL" level="DEBUG" /></configuration>Ballerina
D
10

I was also facing this in my Spring boot app. My case is like below: Outter method annotated with @Transaction. Inside this, i have two different method: Method 1 is deleting records which is also having @Transaction. Method 2 is reading the same records , also annotated with @Transaction. Here issue occur because by default @Transaction annotation support Propagation.REQUIRED which uses current Transaction. So In Method 2 when i try to read the data,it will obviously get Stale exception. The fix which work for me is i annotate Method 1 with @Transactional(propagation = Propagation.REQUIRES_NEW)

So that Method 2 always uses a separate Transaction which will not have Stale data.

Decomposition answered 26/8, 2019 at 10:37 Comment(0)
P
2

I ran into similar problem, where I was trying to save an object where his id was a primitive field (long), and at the time of create the object, the id was set to 0 by default, and Hibernate assumed I wanted to update the row with id = 0 (which obviously doesn't exist).

My solution was change the id field to Long (wrapper), and that way, when I create a new instance the id is set to null, and Hibernate understands I am inserting a new element to the database.
I hope it helps. Thanks.

Punk answered 27/5, 2015 at 20:25 Comment(0)
G
2
  • I got this error because I wanted to update data and I used

    service.update(user);

  • But then for testing purpose I cleared the User table and forgot to change the method to

    service.saveOrUpdate(user);

  • Thus I changed it and the issue was solved.

Grisham answered 31/5, 2018 at 4:58 Comment(0)
P
2

Check if the variable of the Object, that is mapped to the hibernate as Id (which uses a generator class) is not containing any stale value in the first place.

If the record is been deleted by any another thread or operation, but your Id variable is still containing the stale value and when you go for updating the record in the DB, it gives you this exception as there will be no record for the given id in the DB and hence you will have to save the object instead of updating, as there is no scope for updating the record in the first place

Or else

Set the id as null when your are using saveOrUpdate method.

Platinize answered 13/7, 2018 at 6:7 Comment(0)
C
2

I had the similar issue and when i added cascade='save-update' it resolved my issues.

This is my fix worked with CF Application.

Centrosymmetric answered 2/1, 2019 at 20:5 Comment(1)
CF...cloud foundry? canadian forces?Airfield
S
1

Just type save instead of saveOrUpdate in your hibernate query. This is due to previous logs your class is generating some other ID which was previously stored in your table. So hibernate tries to update with same ID and it finds no row with that ID so it gives a staleStateException.

Swordsman answered 16/2, 2015 at 6:1 Comment(0)
B
1

100 % Solution : 1 make sure id in table is auto increment all your foreign keys are not null scope is session

Bondstone answered 18/12, 2016 at 13:15 Comment(0)
C
1

some Times we use generator class to generate primary key of a row... but we add it force in program at time we will get 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");
           }
Checani answered 5/6, 2018 at 11:8 Comment(0)
D
1

Specify below annotaion attribute inside parent entity class:-

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

@OneToMany(targetEntity = PhoneNumber.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
Dung answered 4/11, 2018 at 15:51 Comment(0)
P
1

One of the scenarios when this exception can occur is when you use spring-data-jpa to persist data in a table which has partitioning enabled.

In that case if you use the crudrepository's save method, you will get this exception. The reason being, under the hood, spring JPA uses hibernate to fire the sql query. If you are inserting the data then this error will occur because insert statement returns "0 rows inserted" as the response of insert statement execution(only when partition is enabled). Hibernate expects 1 to be returned and since it doesn't gets it, it rollback the inserted row.

I would suggest if you are getting this kind of error, then connect to the database and fire the sql query manually from the console and check the response. you should be able to investigate further in your problem.

Another workaround which you can implement in your spring/java/hibernate project is to use the Entity Manager to fire native sql query.

Piglet answered 14/6, 2020 at 5:28 Comment(0)
E
0

add a cascade for update. will solve the issue if foreign keys are involved.

Enabling answered 3/2, 2017 at 13:39 Comment(0)
T
0

If Primary Key in a Table is mentioned as auto incremented and you forced to Give value explicitly it will throw Stale state exception.

Tinkling answered 7/1, 2019 at 15:8 Comment(0)
G
0

this exception is mostly occurs when we perform UPDATE operation In hibernate. if we have mention ID as PRIMARY KEY & AUTO_INCREMENT and we are using another id to update the data tends to cause exception...PRIMARY KEY MUST BE SAME

in simple layman language while performing Update operation ID will be same rest data can be change ................................ or use cascade property to change ID if u wish

Gelation answered 4/8, 2021 at 14:18 Comment(0)
A
0

If it is while delete operation for @Entity: check you have not duplication of JPA bindings(@..to..) to the same related records. In this case JPA implementation can try to delete the same referenced record twice. I got this problem using Hibernate+SpringData.

Antisocial answered 2/3, 2022 at 7:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.