要实现我的 SessionFactory 和 ConnectionProvider,不深入了解该体系结构是不行的,先从
源代码分析开始:
首先从 org.hibernate.cfg.Configuration.java 开始,使用 Hibernate 框架实现应用程序,
首先就要与 org.hibernate.cfg.Configuration 打交道,要使用
Configuration.buildSessionFactory()方法获得一个 SessionFactory,截取代码片段如下:
1public SessionFactory buildSessionFactory() throws HibernateException {
2
3 return new SessionFactoryImpl(
4 this,
5 mapping,
6 settings,
7 getInitializedEventListeners()
8 );
9 }
上 面 的 代 码 片 断 省 略 了 读 取 Hibernate 配 置 的 代 码 , 从 这 个 我 们 可 以 知 道 ,
Configuration 类 buildSessionFactory() 方 法 实 际 上 返 回 了 SessionFactory 接 口 的 实 现
SessionFactoryImpl。
当我们得到了一个 SessionFactory 接口的实现 SessionFactoryImpl,就要调用它的
getCurrentSession() 方 法 来 获 得 一 个 Session , 接 下 来 转 到
org.hibernate.impl.SessionFactoryImpl.java,来看看 getCurrentSession()方法的实现,代码片
段如下:
1 public org.hibernate.classic.Session getCurrentSession() throws HibernateException {
2 if ( currentSessionContext == null ) {
3 throw new HibernateException( "No CurrentSessionContext configured!" );
4 }
5 return currentSessionContext.currentSession();
6 }
在 该 方 法 中 , SessionFactoryImpl 将 获 得 Session 的 工 作 委 托 给 了
currentSessionContext.currentSession(),currentSessionContext 为何物?其定义为:
org.hibernate.context.CurrentSessionContext;在 SessionFactoryImpl 的构造函数中,可以看到:
currentSessionContext = buildCurrentSessionContext();
马上追溯到 buildCurrentSessionContext()方法,代码片段如下:
1 private CurrentSessionContext buildCurrentSessionContext() {