Hi,
I'm facing a common problem with cascade update/delete. I have a web application in which the user loads an object from a session, makes some operations on it (delete and add a new child to the object for example) and then persists the object into the database. Seems to be simple and I have read a lot of articles about this issue. However - it does not work correctly for me.
I will try to explain what I can see in the logs while debuging the problem.
1. A spring's formBackingObject method is invoked
- the session opens
- object is loaded
- the session closes
Now the object is loaded into the form and it is detached now. User changes the object in a standard spring form. Then he submits the form.
2. A spring's formBackingObject method is invoked once again. So:
- the session opens
- object is loaded
- the session closes
3. Now the spring's onSubmit method is invoked. The object seems to be detached for me so I am using the merge method to persist the object into the database.
As I could expected (
http://docs.jboss.org/hibernate/stable/core/reference/en/html/objectstate-saveorupdate.html) the object should be loaded and then persisted. And that's right:
- the session opens
- object is loaded
- object is merged
- the session closes
The problem occurs when the user tries to remove an object from the collection, add a new one and then submit the form. So in the database I have a Parent with a collection of Childs [Child{id=123, name='something'}] and the object to merge has a collection of Childs [Child{id=null, name='anything'}].
After trying to merge I have an exception:
Code:
2009-05-27 16:58:22,215 2135904 ERROR [org.hibernate.event.def.AbstractFlushingEventListener] (http-8080-1:) 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) ...
What I am doing wrong? Strange for me is that when the user adds two Childs and removes only one Child everything is ok. The problem occurs only when the user removes exactly the same number of Childs as the number of new Childs he adds in the form.
If the code is needed - I will paste it of course.
Thanks for any suggestions,
Regards,
Pawel