查看: 4682|回复: 1
打印 上一主题 下一主题
收起左侧

请问下飞哥关于Hibernate绑定session到当前线程的原理,为什么写thread?

[复制链接]

1

主题

1

帖子

16

积分

新手上路

Rank: 1

积分
16
楼主
跳转到指定楼层
发表于 2017-10-5 21:58:56 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 纯情小飞飞 于 2017-10-5 22:07 编辑

请问下飞哥关于Hibernate绑定session到当前线程的原理,为什么写thread?

在hibernate.cfg.xml中要这样配置,才能获取当前线程的Session

  1. <property name="hibernate.current_session_context_class">thread</property>



配置完成之后,这个才生效:
  1. /**
  2.    * 把session对象绑定到当前线程里
  3.    * @return
  4.    */
  5.   public static Session getCurrentSession(){
  6.     return sessionFactory.getCurrentSession();
  7.   }




麻烦飞哥解释下,非常感谢。


回复

使用道具 举报

566

主题

713

帖子

3827

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
3827
沙发
发表于 2017-10-5 22:38:30 | 只看该作者
小飞飞,您好!

你问的这个问题,我现在给你解释下。

在hibernate.cfg.xml中配置的所有property其实都是为了创建SessionFactory而准备的,首先这一点要明确。

再次,我们看下SessionFactory的获取当前线程的session的方法,这个时候需要跟一下源码。
如下图:




这个session工厂的1225行有个buildCurrentSessionContext()的方法,可以看下这个方法【我用的Hibernate的版本是5.0.7】

如下图:



这里可以看到底层使用的是ThreadLocal的方式绑定Session到当前线程上,而Hibernate框架自己封装了一个SessionContext上下文对象,用于绑定当前线程的session对象,在代码里面已经写死了thread这个字符串,所以需要配置上这个字符串。

如果配置了thread  这里返回的是:  new ThreadLocalSessionContext( this );

而getCurrentSession方法,就是判断通过那个context返回当前线程session,如下图:



  1. public final class SessionFactoryImpl implements SessionFactory, SessionFactoryImplementor {

  2. private final transient CurrentSessionContext currentSessionContext;

  3. public org.hibernate.classic.Session getCurrentSession() throws HibernateException {
  4.     if ( currentSessionContext == null ) {
  5.       throw new HibernateException( "No CurrentSessionContext configured!" );
  6.     }
  7.     return currentSessionContext.currentSession();
  8.   }
  9. }



不知道我这样解释,清楚了没有?


还有就是,你可以看看:org.hibernate.context.ThreadLocalSessionContext 的源码,里面用了ThreadLocal和动态代理技术绑定Session到当前线程上。


自己看看哈。





本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

  • 打开微信扫一扫