ibatis-user-java mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Alistair Young" <alistair.j.yo...@gmail.com>
Subject Pseudo-nesting of transactions
Date Wed, 16 Apr 2008 13:18:50 GMT
I have a question about nesting iBATIS transactions.  Or, at least,
being able to write methods which will work in an iBATIS transactional
context whether or not one has been imposed externally.

Consider the following bit of sample code:

   sqlMap.startTransaction();
   sqlMap.update("XXX", xxx);
   doProcessing();
   sqlMap.commitTransaction();
   sqlMap.endTransaction();

And suppose that my doProcessing() method looks like this:

   sqlMap.startTransaction();
   sqlMap.update("YYY", yyy);
   sqlMap.commitTransaction();
   sqlMap.endTransaction();

If I execute this code, I'll get an exception because a nested
transaction is being attempted on the sqlMap.

However, what I really want to happen is for the database operations
in my doProcessing() method to join the existing iBATIS transaction,
if one happens to be open (so it is not true nesting).  Something like
this:

   boolean txnAlreadyOpen = sqlMap.isTransactionOpen();
   if (!txnAlreadyOpen) {
      sqlMap.startTransaction();
   }
   sqlMap.update("YYY", yyy);
   if (!txnAlreadyOpen) {
      sqlMap.commitTransaction();
      sqlMap.endTransaction();
   }

Except, of course, the isTransactionOpen() method doesn't actually
exist.  So I find myself pondering the following code...

   boolean txnAlreadyOpen = false;
   try {
      sqlMap.startTransaction();
   } catch (NestedSQLException x) {
      if (x.getCause() instanceof TransactionException) {
         txnAlreadyOpen = true;
      } else {
         throw x;
      }
   }
   // ... as before

(I appreciate that there are subtleties here when it comes to managing
rollback etc., but one thing at a time...!)

Is there a better way of dealing with this?

Cheers,


Alistair.

Mime
View raw message