hibernate获取session的两个方法(笔记)

通过SessionFactory获取 Session的两个方法 openSession() 一个 getCurrentSession();

1.      openSession() 是获取一个新的session

2.      getCurrentSession () 获取和当前线程绑定的session,换言之,在同一个线程中,我们获取的session是同一session,这样可以利于事务控制

如果希望使用getCurrentSession 需要配置 hibernate.cfg.xml中配置.

3.      如何选择

原则:

       ①如果需要在同一线程中,保证使用同一个Session则,使用getCurrentSession()

       ②如果在一个线程中,需要使用不同的Session,则使用opentSession()

4.      通过 getCurrentSession() 获取的session在事务提交后,会自动关闭,通过openSession()获取的session则必须手动关闭

5.      如果是通过getCurrentSession() 获取 sesssion ,进行查询需要事务提交.

原文地址:https://www.cnblogs.com/jggz/p/2954861.html