When attempting to saveOrUpdate() a number of objects, Hibernate assigns the primary key to the objects as they are inserted.
Unfortunately, if an exception is thrown by, say, the 4th saveOrUpdate() call, the first 3 objects inserted still have their primary key set even after rolling back the transaction. The problem with that is that when a saveOrUpdate is retried for those 3 objects, Hibernate will think they should be
updated instead of
inserted since the primary key is no longer null.
Is there a way around this problem other than manually nullifying the primary keys of all the objects after rolling back the transaction? Perhaps some call I'm not aware of which will nullify the PK of all saveOrUpdate()ed objects during the transaction?
Thanks for your help.
Hibernate version: 3
Code:
Transaction tx = s.beginTransaction();
try {
s.saveOrUpdate(user);
Set<Children> children = user.getChildren();
if (children!=null) {
Iterator childIterator = children.iterator();
while (childIterator.hasNext()) {
s.saveOrUpdate(childIterator.next());
}
}
tx.commit();
}
catch (Throwable t) {
tx.rollback();
// NEED SOMETHING HERE TO NULLIFY PKs IN EVENT OF MID-SAVE EXCEPTION
throw new CLockException("An error occurred while saving the user.", t);
}