In an interview someone asked me : How do we manage 2 transactional/dao methods in a single transaction. Desired capabilities:
- If anyone of them fails we need to rollback both methods.
- Both of the methods can be called separately attached with a single transaction.
- The management should be on DAO layer, not on service layer.
I think : the question relates to spring transaction management.
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() {
}
}
4
Ignoring spring and frameworks in my answer….. just the basic idea of using function parameters. I’m sure the concept could apply within [insert framework here].
You would need to handle the commit/rollback outside of the 2 DAO methods. The 2 methods would need to take the transaction/connection as input.
psuedo code:
bool method1(Tran t) { /* stuff */}
bool method2(Tran t) { /* stuff */ }
callingMethod() {
Tran t = null;
try {
t = new Conn().open().startTran();
if(method1(t) && method2(t))
t.commit();
else
t.rollBaack();
}
catch(ex) { t.rollBack(); }
finally { t.closeConn(); }
}
2
There is a chance that two methods should work independently also at the same time there might run in a same transaction.So we need to use Propagation-Required.
If the transaction has to run in same transaction then it will use the first transaction else a new transaction is created if invoked independently.
Correct me if I am wrong.
1