开发者

problem in hibernate DAO (session already closed!!)

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 Session in your MyDAO, you're probably best off holding onto just the SessionFactory, and getting a session from is when needed, by defining your getSession method in MyDAO as

public Session getSession() {
   return sessionFactory.getCurrentSession();
}

or just save nothing related to session handling in MyDao at all and use

public Session getSession() {
   return HibernateUtil.getSessionFactory().getCurrentSession();
}

A 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜