美文网首页
Hibernate绑定Session到本地线程

Hibernate绑定Session到本地线程

作者: Michael_林 | 来源:发表于2017-04-29 17:24 被阅读88次

    绑定本地的Session

    1. 之前在讲JavaWEB的事务的时候,需要在业务层使用Connection来开启事务,

      • 一种是通过参数的方式传递下去
      • 另一种是把Connection绑定到ThreadLocal对象中
    2. 现在的Hibernate框架中,使用session对象开启事务,所以需要来传递session对象,框架提供了ThreadLocal的方式

      • 需要在hibernate.cfg.xml的配置文件中提供配置

        • <property name="hibernate.current_session_context_class">thread</property>
      • 重新HibernateUtil的工具类,使用SessionFactory的getCurrentSession()方法,获取当前的Session对象。并且该Session对象不用手动关闭,线程结束了,会自动关闭。
        public static Session getCurrentSession(){
        return factory.getCurrentSession();
        }

      • 注意:想使用getCurrentSession()方法,必须要先配置才能使用。

    相关文章

      网友评论

          本文标题:Hibernate绑定Session到本地线程

          本文链接:https://www.haomeiwen.com/subject/afnzzttx.html