Hibernate之session理解
getCurrentSession创建的session会和绑定到当前线程,而openSession不会。 getCurrentSession创建的线程会在事务回滚或事物提交后自动关闭,而openSession必须手动关闭
这里getCurrentSession本地事务(本地事务:jdbc)时 要在配置文件里进行如下设置
说明:两个session都必须开启事务和关闭事务,如果没有。在getCurrentSession会抛出异常
openSession不会出现异常,但是数据会回滚
* 如果使用的是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事务(jta事务)
<property name="hibernate.current_session_context_class">jta</property>
getCurrentSession () 使用当前的session
openSession() 重新建立一个新的session
测试:
Configuration cfg = new Configuration().configure(); //创建SessionFactory SessionFactory factory = cfg.buildSessionFactory(); Session s = factory.getCurrentSession(); s.beginTransaction(); s.save(new User()); System.out.println("=====================" + s); System.out.println(factory.getCurrentSession() == s); //true (绑定线程) s.getTransaction().commit(); System.out.println("session is open :" + s.isOpen()); //已关闭 System.out.println("------------------------"); Session session = factory.openSession(); session.beginTransaction(); session.save(new User()); System.out.println("=====================" + session); System.out.println(factory.openSession() == session); // false session.getTransaction().commit(); System.out.println("session is open :" + session.isOpen()); //未关闭