Hibernate Delete Error: Batch Update Returned Unexpected Row Count
dao, hibernate, java, methods
Solution
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.
Problem
I wrote this method below that is suppose to delete a member record from the database. But when I use it in my servlet it returns an error. MemberDao Class ``` public static void deleteMember(Member member) { Session hibernateSession = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx = hibernateSession.beginTransaction(); hibernateSession.delete(member); tx.commit(); } ``` Controller Part ``` if(delete != null) { HttpSession httpSession = request.getSession(); Member member = (Member) httpSession.getAttribute("member"); MemberDao.deleteMember(member); nextPage = "ledenlijst.jsp"; } ``` HTTP Status 500 ``` org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1 ``` Sometimes it even throws this error when I try to execute the page multiple times. ``` org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update ``` Does anybody know what exactly is causing these errors?