【问题标题】:problem in hibernate DAO (session already closed!!)hibernate DAO 中的问题(会话已经关闭!!)
【发布时间】:2026-02-16 21:15:01
【问题描述】:

我已经实现了如下DAO,

//伪代码

public MyDAO{

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

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

现在我已经使用 dao 保存单个对象,它工作正常。现在如果在单独的事务中保存两个对象,我会收到错误消息“会话已关闭”

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 的会话来启动事务

【问题讨论】:

  • 现在是美国的周六清晨,我们中的许多人可能都睡着了。回复并不总是很快。

标签: hibernate session


【解决方案1】:

与其试图在MyDAO 中保留Session,不如只保留SessionFactory,并在需要时获取会话,方法是在中定义getSession 方法MyDAO作为

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

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

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

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

【讨论】:

  • 自几小时前标题更改以来,我没有看到任何编辑。您当前的问题是什么?