Hibernate Delete Error: Batch Update Returned Unexpected Row Count
The error can be caused by several things. I'm not taking the credit for it, found it here.
- Flushing the data before committing the object may lead to clear all object pending for persist.
- If object has primary key which is auto generated and you are forcing an assigned key
- if you are cleaning the object before committing the object to database.
- Zero or Incorrect ID: If you set the ID to zero or something else, Hibernate will try to update instead of insert.
- Object is Stale: Hibernate caches objects from the session. If the object was modified, and Hibernate doesn’t know about it, it will throw this exception — note the StaleStateException
Also look at this answer by beny23 which gives a few further hints to find the problem.
- In your hibernate configuration, set hibernate.show_sql to true. This should show you the SQL that is executed and causes the problem.
- Set the log levels for Spring and Hibernate to DEBUG, again this will give you a better idea as to which line causes the problem.
- Create a unit test which replicates the problem without configuring a transaction manager in Spring. This should give you a better idea of the offending line of code.
The exception
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
use to be thrown when Hibernate notice that the entity he wants to flush to the database isn't exactly as it was at the beginning of the transaction.
I described more in details two different use cases that happen to me here.