I'm having trouble trying to save objects after having received a StaleObjectStateException. Here's the background:
I have three classes: Class A which contains a Set (one-to-many, cascade=all) of class B which contains an instance (many-to-one, cascade=all) of class C.
Class A has a version property for recognizing stale objects.
I have several message-driven beans running in parallel, all modifying the same instance of A, but each modifying a separate instance of B and associating with it a new instance of C.
So, in a MDB I have something like this:
Code:
void saveObjects(C c) {
// NOTE: 'c' is a transient object which I can't duplicate.
boolean success = false;
while (!success) {
success = true;
session = // get new Hibernate session
session.beginTransaction();
try {
A a = // retrieve the instance of a from the database
a.setSomeFieldValuesHere...
B b = // get correct instance of B from 'a'
b.setC(c); // associated 'b' with new transient object 'c'.
session.saveOrUpdate(a);
session.commit();
} catch (StaleObjectException e) {
success = false;
session.rollback();
} finally {
session.close();
}
} // end of while loop
} // end of saveObjects
Ok, so if too many MDB's are running in parallel, I get StaleObjectStateException's, as expected, and try to repeat the saving task. My problem is that if the save fails the first time, it seems that the ID values of object 'c' are set to new values instead of the 0's used to indicate an unsaved object, so when trying to save it a second time I think 'c' is treated as an already persisted object instead of a new object, and I receive an error like:
Caused by: COM.ibm.db2.jdbc.DB2Exception: [IBM][CLI Driver][DB2/SUN] SQL0530N The insert or update value of the FOREIGN KEY "DB2.B.FKABCDEFG" is not equal to any value of the parent key of the parent table. SQLSTATE=23503
Other than manually resetting the ID of 'c' to 0, and iterating through all its contained cascaded objects and setting their id's back to 0 - which is not trivial in my case - is there any way to get around this problem?
Thanks for any help....
Luke
Code: