I’ve been reading about the sun blueprint GenericDAO implementation and Gavin King’s take on this for use with Hibernate. It seems he doesn’t mention anything about transaction handling:
public abstract class GenericHibernateDAO<T, ID extends Serializable> {
protected Session getSession() {
return HibernateUtil.getSessionFactory().getCurrentSession();
}
public T makePersistent(T entity) {
getSession().saveOrUpdate(entity);
return entity;
}
}
I’m puzzled as to where I should put the start/end of the transaction. Currently they are inside the DAOs that extend this GenericHibernateDAO
public class FooHibernateDAO extends GenericHibernateDAO<Foo, Long> {
public Foo saveFoo(Foo foo) {
getSession().beginTransaction();
makePersistent(foo);
getSession().getTransaction().commit();
}
}
Should the transaction handling be managed by the caller of the DAO in the application tier?
Generally the best practice is to manage transactions in service layer not in DAO layer. Each DAO method generally handles one specific operation and a service method aggregates them in one transaction.