Back Forum Reply New

How to extend transaction scope to multiple quot;savequot;s in a loop?

mit()quot;.  I'm not certain whether I have to do anything else here.  One code sample I saw calls quot;HibernateUtil.closeSession()quot; after the quot;commit()quot; call.

Am I on the right track here?  Is this the right way to do this?  Is there a better way?

You can mark the method that starts the loop as transaction - this will make the save methods to become part of the ongoing transaction and thus they can all commit at once.
Besides the declarative approach you can place the whole loop inside a transaction in a programmatic way (see the reference documentation for more info). Basically you'll use the TransactionTemplate and TransactionCallback and place the loop inside it.

Actually, I believe I've resolved this by just adding a new quot;savequot; method to my DAO class, which takes a list of the objects to save, instead of a single one.  The code that calls the DAO just puts the created objects into the list and calls the save method at the end, instead of calling quot;savequot; on each one in the loop.

if the loop-wrapping method is transactional, and the saveSingle() method are transactional as well (with REQUIRED or SUPPORTED), then each saveSingle() invocation will not trigger TX commit.
From the performance PoV, there shouldn't be any difference between this approach and your new saveList(list) method. Of course, if you are not using batch-updates there.
¥
Back Forum Reply New