Using transaction management outside the DAO is not a good idea. It
should be done inside the DAO itself. We can use a Strategy Pattern to
plug-in the transactional behaviour into the DAOs.
Declare a interface as
public interface TransactionStrategy {
public void beginTransaction();
public void commit();
}
Have an implementor like,
public class DefaultTransactionStrategy {
public void beginTransaction(){
HibernateUtil.getSessionFactory().getCurrentSession()
.beginTransaction();
}
public void commit(){
HibernateUtil.getSessionFactory().getCurrentSession()
.commit();
}
}
Now in the DAOs, you can have a instance variable declared for the
transaction strategy. Like
public class xyzDAO{
private TransactionStrategy transaction = null;
public xyzDAO(){
transaction = new DefaultTransactionStrategy();
}
public void insert(Object obj){
transaction.beginTransaction();
// Do some work
session.load(...);
session.persist(...);
transaction.commit();
}
public void setTransactionStrategy(TransactionStrategy strategy){
transaction = strategy;
}
}
Thus we can move the transaction management code to a strategy class
which will be used inside the DAOs.
In future, if you want to switch to a JTA Transaction, then you can
create a new transaction strategy for the same.
Also these strategies can be set to DAOs in
HibernateDaoFactory.instantiateDAO(Class clazz), where we have set the
session. Also, we can take the strategy info from a property file as
well. So based on a property in the property file, you can create a
strategy and set it to the DAOs.
Note: Strategy class can also accept the session through its constructor
if you define one which accepts it. |