11

If I have this:

Start transaction1
  Call someMethod
    Start transaction2
       Call someOtherMethod
          Start tranaction3

If transaction3 rolls back, do transaction2 and transaction1 roll back also?

Thanks!

1 Answer 1

7

While Hibernate does not explicitly support nested transactions, using a JDBC 3.0 driver that is able to create savepoints can achieve this.

Create a Connection at the start of the program when the SessionFactory is created. At this point you also create a Savepoint that serves as the starting point for the transaction.

Then you move through each nested transaction. For each nested transaction, you should create another different savePoint i.e. a rollingSavePoint which you can rollback to should that nested transaction fail. Then for that same nested transaction, open a session that uses the Connection you created at the start (i.e. Session nestedTransaction = SessionFactory.openSession(connection)) and make your updates. Flush the session and close it.

After all nested transactions are completed, call connection.commit() to commit the global transaction and close it. Close the sessionFactory as per usual and continue to do whatever else you need to do.

Some things to note:

  • Obviously autoCommit mode must be off, otherwise each time you call flush you'll be commiting straight to the DB.
  • If you're also doing searching or other operations you'll want to open other sessions that use their own connections. Ensure that you set the Transaction isolation level to READ_UNCOMMITED or else you'll probably be facing locking problems.
  • Of course you should commit periodically or else your database will have issues, or you can increase the size of database virtual memory.

If you are using spring you can also use Spring Propagation.Check this link http://www.byteslounge.com/tutorials/spring-transaction-propagation-tutorial

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.