Hibernate version:
3.0.3
I have written an Interceptor to perform invariant checks on flushed entities during "preFlush". If any of the flushed entities are invalid, a RT exception is thrown from this method. However, I have run into a problem in cases where new entities are invalid.
Code:
public static void saveBank(final Bank bank) {
HibernateUtil.beginTransaction();
HibernateUtil.currentSession().saveOrUpdate(bank);
HibernateUtil.commitTransaction();
}
The problem is that the primary key is set on the new objects (by hibernate using a hilo algorithm) in the object graph before the preflush call and they are never unset on a validation failure. This causes problems downstream once the user has corrected the problem and attempts to save the changes. At this point, hibernate sees the primary key is already set and attempts to update a row that does not exist.
Perhaps the following code is easier to understand, it too "fails".
Code:
Bank bank = new Bank(); //will fail aba number is not nullable.
HibernateUtil.beginTransaction();
HibernateUtil.currentSession().saveOrUpdate(bank);
assertNotNull(bank.getBankId());
HibernateUtil.rollbackTransaction();
assertNull(bank.getBankId()); //primary key is non-null.
I would think that the rollback would also rollback any changes to the primary key. Is this simply not supported? It is not trivial for me to determine if an insert/update is actually required for all objects in the object graph.