How to Manage 2 DAO Methods in a Single Transaction

daoservicespringtransaction

In an interview someone asked me : How do we manage 2 transactional/dao methods in a single transaction. Desired capabilities:

  1. If anyone of them fails we need to rollback both methods.
  2. Both of the methods can be called separately attached with a single transaction.
  3. The management should be on DAO layer, not on service layer.

I think : the question relates to spring transaction management.

Best Answer

First of all, transaction management should be done on service layer, not on DAO layer as that would create a lot of performance overhead (to deal with appropriate transaction isolation level and propagation at each different method). Also, the scope of a unit of work comes from the service layer instead of the data access layer: imagine performing a business process that needs to deal with 2 or more DAOs.

There is a lot of discussion in the Internet that points in that direction as here, here and here.

Anyway, since it's an interview let's accept the question as is. From my point of view, you would be using the @Transactional annotation (or the XML configuration) in both methods and with a transaction propagation with REQUIRED value. That way, when any of those methods is invoked and if no previous transaction exist, a new transaction will be created:

@Transactional
class MyDAO {

   @Transactional(propagation = REQUIRED)
   public void foo() {
   }

   @Transactional(propagation = REQUIRED)
   public void bar() {
   }

}