I know (based on various forum discussions) that you've been asked questions along this vein multiple times, but I'm pretty stumped and maybe you can help:
The scenario I'm struggling with is pretty simple; I need to insert records into two different tables within the same transaction. The problem is that, for some reason, when an exception is thrown because of a failure to insert into the second table and I roll back the transaction, the record remains in the first table. Here's the code snippet:
try { session = sessionFactory.openSession(); tx = session.beginTransaction(); session.persist(test1); session.persist(test2); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } finally { session.close(); }
In trying to figure out the problem, I even changed the FlushMode to COMMIT and explicitly did a session.flush() prior to the tx.commit(). The result was that even though tx.commit() is never executed, because an exception is thrown when session.flush() is executed, the test1 record remains in the table!? Again, here's the code:
try { session = sessionFactory.openSession(); session.setFlushMode(FlushMode.MANUAL); tx = session.beginTransaction(); session.persist(test1); session.persist(test2); session.flush(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } finally { session.close(); }
Any light you can shed on this?
Thanks!
|