hibernate.cfg.xml中的配置
<property name="hibernate.current_session_context_class">thread</property>
层序中获取通过SessionFactory获取session时使用getCurrentSession()
@Test
public void test01() {
Session s1 = HibernateUtils.openSession();
Session s2 = HibernateUtils.openSession();
System.out.println(s1 == s2);//false
Session s3 = HibernateUtils.getCurrentSession();
Session s4 = HibernateUtils.getCurrentSession();
System.out.println(s3 == s4);//true
}
与当前线程绑定的Session会自动关闭, 当Transaction 提交后,Session 会自动关闭
@Test
public void test02() {
Session session = HibernateUtils.getCurrentSession();
Transaction transaction = session.beginTransaction();
session.get(Customer.class, 1);
transaction.commit();
//不需要手动关闭,org.hibernate.SessionException: Session was already closed
session.close();
}