OpenSession()和getCurrentSession的联系和区别

来源:互联网 发布:天天特价淘宝 编辑:程序博客网 时间:2024/05/17 09:34
我们获取链接数据库的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则必须手动关闭


0 0