刚开始用Hibernate,之前的有些理解是错误的,今天又纠正一个;对于getCurrentSession虽然看了文档
Obtains the current session. The definition of what exactly "current" means controlled by the
CurrentSessionContext impl configured for use但是还是以为向操作普通session一样的去操作,结果造成程序运行出错。
通过getCurrentSession返回的session是commit之后自动关闭的,不能再调用session.close方法。如下面的代码是错误的:
/* (non-Javadoc)
* @see com.csair.hunan.pss.web.dao.UserManage#saveUser(com.csair.hunan.pss.web.dao.User)
*/
public boolean saveUser(User user) {
Session session = adapter.getSessionFactory().getCurrentSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.saveOrUpdate(user);
tx.commit();
return true;
} catch (HibernateException he) {
if(tx != null) {
tx.rollback();
}
return false;
} finally {
session.close();
}
}
* @see com.csair.hunan.pss.web.dao.UserManage#saveUser(com.csair.hunan.pss.web.dao.User)
*/
public boolean saveUser(User user) {
Session session = adapter.getSessionFactory().getCurrentSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.saveOrUpdate(user);
tx.commit();
return true;
} catch (HibernateException he) {
if(tx != null) {
tx.rollback();
}
return false;
} finally {
session.close();
}
}
解决的方法是把finally块的代码去掉,要么获取session的方式改为openSession();当然前者的优势明显。
仔细看了hibernate的参考文档:
The "current session" refers to a Hibernate Session bound by Hibernate behind the scenes, to the transaction scope. A Session is opened when getCurrentSession() is called for the first time and closed when the transaction ends. It is also flushed automatically before the transaction commits. You can call getCurrentSession() as often and anywhere you want as long as the transaction runs. To enable this strategy in your Hibernate configuration:
见:http://www.hibernate.org/42.html
我仍不确定我上面的代码写得是否正确,但是暂时来看执行是不成问题的,说是currentSession绑定到Java Thread,我单线程的程序呢,应该没有问题,参考文档中对于getCurrentSession的用法是这样的:
try {
factory.getCurrentSession().beginTransaction();
// Do some work
factory.getCurrentSession().load(...);
factory.getCurrentSession().persist(...);
factory.getCurrentSession().getTransaction().commit();
}
catch (RuntimeException e) {
factory.getCurrentSession().getTransaction().rollback();
throw e; // or display error message
}
它在每一行代码都用getCurrentSession取得当前的session, 而我的代码中是在最开始取得这个session,现在疑惑的是如果是多线程的程序,那么通过我那样获得的currentSession是否还有效?
factory.getCurrentSession().beginTransaction();
// Do some work
factory.getCurrentSession().load(...);
factory.getCurrentSession().persist(...);
factory.getCurrentSession().getTransaction().commit();
}
catch (RuntimeException e) {
factory.getCurrentSession().getTransaction().rollback();
throw e; // or display error message
}
它在每一行代码都用getCurrentSession取得当前的session, 而我的代码中是在最开始取得这个session,现在疑惑的是如果是多线程的程序,那么通过我那样获得的currentSession是否还有效?

没有评论:
发表评论