I have implemented DAO as follows,
//pseudoCode
public MyDAO{
private Session session;
MYDAO{
this.setSession(HibernateUtil.getSessionFactory().getCurrentSession());
}
public void save(MyObj obj){
//save obj in db
}
}
Now i have used the dao to save a single object it works fine.Now if save two object inside seperate transcation i get a error saying “session is already closed”
EG
Feature feature = new Feature();
feature.setFeatureName("testf333");
FeatureDAO featureDAO = new FeatureDAO();
Transaction tx = featureDAO.getSession().beginTransaction();
featureDAO.makePersistent(feature);
tx.commit();
System.out.println("successfully save in db " + feature.getId());
tx = featureDAO.getSession().beginTransaction(); //getting error here
Feature feature4 = new Feature();
feature4.setFeatureName("4444");
featureDAO.makePersistent(feature4);
tx.commit();
System.out.println("successfully save in db " + feature.getId());
I think this problem can be solved by checking if session is closed .But where can i set a new session because i use the session from DAO to start a transcation
Rather than trying to hold onto the
Sessionin yourMyDAO, you’re probably best off holding onto just theSessionFactory, and getting a session from is when needed, by defining yourgetSessionmethod inMyDAOasor just save nothing related to session handling in
MyDaoat all and useA hibernate session is tied to a specific thread and closed on commit, but the session factory’s
getCurrentSession()method gets a new session as needed so that you don’t have to worry about it.