Who hasn’t seen the StaleState or NonUniqueObject exceptions while doing persistency with Hibernate? They tell you there might be a problem in your software design but according to their names, no clue what can be wrong. Here’s a simple �what is happening and ho to get around it’ recipe to solve this.
The StaleStateException describes the inconsistency of your objects versus the state of these objects in your database. This exceptions typically occurs when deleting an object that already was been deleted in the database. Therefore the exception will be something like:
Batch update returned unexpected row count from update….
Incorrect usage of your un-save strategy of your class will be the cause of this exception. Your application is not properly implemented considering your data manipulation saving strategy.
Example:
Suppose School and Student are common classes in your application. In two views school and student relationship can be adjusted. Only in one view the adjustment is saved by user interaction (push the save button). So in case of a deletion, the objects are deleted from the session but not directly saved. When flushing the Session, Hibernate will try to synchronize the state with the database and that will fail. The org.hibernate.jdbc.BatchingBatcher will check the expected row count and throws the exception. Mixing sequence scenarios with Junit is the best way to tackle this issue before functional testing.
NonUniqueObjectException will be thrown when two different instances of the same Java class with a particular identifier are in the scope of a single Session. The simple solution is not to load an object to the session if there is already a reference. Call the saveOrUpdateCopy at the beginning of a transaction to avoid this exception (or merge in Hibernate3).
Another possible issue can be the definition of your mappings. Make your relations unidirectional, this prevents loading from childs object also the parent object
Or by not deleting all objects used in a bidirectional association, for example
parent.getChildren().remove(child);
child.removeParent(parent);
May these tips help in your dive :-)
Resources:
http://www.hibernate.org/hib_docs/v3/api/org/hibernate/StaleStateException.html
http://www.hibernate.org/hib_docs/v3/api/org/hibernate/NonUniqueObjectException.html
http://www.jroller.com/page/maximdim?entry=hibernate_batch_update_returned_unexpected (demonstrate the StateStateExeption with a Junit test)
http://www.hibernate.org/116.html (hibernate common faq)