飞网论坛

标题: 请问下飞哥关于Hibernate绑定session到当前线程的原理,为什么写thread? [打印本页]

作者: 纯情小飞飞    时间: 2017-10-5 21:58
标题: 请问下飞哥关于Hibernate绑定session到当前线程的原理,为什么写thread?
本帖最后由 纯情小飞飞 于 2017-10-5 22:07 编辑

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

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

[code=xml]<property name="hibernate.current_session_context_class">thread</property>[/code]


配置完成之后,这个才生效:
[code=java]/**
   * 把session对象绑定到当前线程里
   * @return
   */
  public static Session getCurrentSession(){
    return sessionFactory.getCurrentSession();
  }[/code]



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



作者: johnny    时间: 2017-10-5 22:38
小飞飞,您好!

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

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

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

[attach]1140[/attach]


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

如下图:
[attach]1141[/attach]


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

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

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

[attach]1143[/attach]

[code=java]
public final class SessionFactoryImpl implements SessionFactory, SessionFactoryImplementor {

private final transient CurrentSessionContext currentSessionContext;

public org.hibernate.classic.Session getCurrentSession() throws HibernateException {
    if ( currentSessionContext == null ) {
      throw new HibernateException( "No CurrentSessionContext configured!" );
    }
    return currentSessionContext.currentSession();
  }
}[/code]


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


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


自己看看哈。










欢迎光临 飞网论坛 (https://bbs.cfei.net/) Powered by Discuz! X3.2