Reputation: 6152
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;
}
Upvotes: 1
Views: 1734
Reputation: 14061
I'd echo axtavt's answer. Just as an additional information, if you are using a Java EE capable container (like JBoss AS), then use the EntityManager which is managed by it. It's specially easy in Java EE 6, with CDI.
Upvotes: 0
Reputation: 242786
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.
Upvotes: 2