我在每个DAL方法中都这样做:
public static Product GetProductByPartNumber(String partNumber)
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Product product = (Product)session.createCriteria(Product.class)
.add(Restrictions.eq("partNumber", partNumber))
.uniqueResult();
session.getTransaction().commit();
return product;
}
这会导致问题,因为延迟加载等原因导致“会话已关闭”错误。
如何让getcurrentSession不获取新会话?
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration().configure();
//configuration.addClass(hsspider.Model.AMCategory.class);
return configuration.buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
thread
我猜这就是问题所在,对getcurrentSession的调用没有使当前会话正确吗?
或者调用transaction.commit();终止会话?
我应该用冲水吗?