I am looking for a good way to manage hibernate session across web application.
My problem is that i dont want to allow session access in the view or API layer.
so i built the following method in my abstract BaseDao class.
the method method
protected static Session getSession() {
if(!session.isOpen()){
session = sessionFactory.openSession();
}else{
session.clear();
}
return session;
}
usage:
public IHibernateBean save(IHibernateBean bean) {
Transaction t = session.beginTransaction();
getSession().saveOrUpdate(bean);
t.commit();
return bean;
}
public IHibernateBean getByPK(Class<?> class1 , Long pk) {
IHibernateBean hibernateBean = (IHibernateBean) getSession().get( class1 , pk );
return hibernateBean;
}
You can use the contextual session obtained via
SessionFactory.getCurrentSession(), see 2.3. Contextual sessions.Also see Generic Data Access Objects for example of typesafe DAO implementation.