【发布时间】: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 的会话来启动事务
【问题讨论】:
-
现在是美国的周六清晨,我们中的许多人可能都睡着了。回复并不总是很快。