hibernate中的session的另外一种获取方法:hibernate3以后给你提供了一种sessionFactory.getCurrentSession()这样拿出来的session是放到ThreadLocal里面的.他不需要你显式的关闭,在线程结束之后他自动关闭,即在事务提交或回滚之后自动关闭.
1、openSession和getCurrentSession的区别?
* openSession必须关闭,currentSession在事务结束后自动关闭
* openSession没有和当前线程绑定,currentSession和当前线程绑定
2、使用currentSession需要在hibernate.cfg.xml文件中进行配置:
* 如果是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</property>
* 如果是全局事务(jta事务)
<property name="hibernate.current_session_context_class">jta</property>
public class UserManagerImpl implements UserManager {
public void addUser(User user) {
Session session = null;
try {
//session = HibernateUtils.getSession();
session = HibernateUtils.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(user);
Log log = new Log();
log.setType("操作日志");
log.setTime(new Date());
log.setDetail("XXX");
LogManager logManager = new LogManagerImpl();
logManager.addLog(log);
Integer.parseInt("adfsadfdsf");
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}
}
}
以上红色部份是可以作为一个事务来运行的.如果出现异常,如Integer.parseInt("adfsadfdsf"); 那么他会自动进行session的关闭