hibernate DAO中的问题(会话已经关闭!!)

时间:2011-07-09 11:06:06

标签: hibernate session

我已经实现了DAO,如下所示,

//伪代码

public MyDAO{

  private Session session;
  MYDAO{
  this.setSession(HibernateUtil.getSessionFactory().getCurrentSession());
  }

  public void save(MyObj obj){
   //save obj in db
  }
}

现在我已经使用dao来保存单个对象它工作正常。现在如果在单独的transcation中保存两个对象我得到一个错误说“会话已经关闭”

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());

我认为这个问题可以通过检查会话是否已关闭来解决。但是我可以在哪里设置新会话,因为我使用来自DAO的会话来开始交易

1 个答案:

答案 0 :(得分:2)

而不是试图抓住Session中的MyDAO,您可能最好只抓住SessionFactory,并在需要时通过定义来获取会话getSession中的MyDAO方法为

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

或者只在MyDao中保存与会话处理无关的任何内容并使用

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

hibernate会话绑定到特定线程并在提交时关闭,但会话工厂的getCurrentSession()方法根据需要获取新会话,因此您不必担心它。