Session是Hibernate持久化操作的基础。Hibernate Session 之与Hibernate,相当于JDBC Connection相对于JDBC。那么Hibernate的Session从哪里来的呢。从代码中我们可以看出来
sessionFactory.openSession();
Hibernate的Session是通过SessionFactory创建出来的。下面我们从代码中来看。
//【1】
public org.hibernate.classic.Session openSession() throws HibernateException {
return openSession(interceptor);
}
//【2】
public org.hibernate.classic.Session openSession(Connection connection) {
return openSession(connection, interceptor); //prevents this session from adding things to cache
}
从上述的两个方法中可以看出,无论你创建session时是否传递参数,程序默认的都会给你加上一个拦截器的设置,这个拦截器从哪儿来的呢?当然是从咱们的配置文件中来。从【2】看出参数是一个connection的连接。
接下来我们看一下这几个方法最终调用的方法是什么:
【最终】
private SessionImpl openSession(
Connection connection,
boolean autoClose,
long timestamp,
Interceptor sessionLocalInterceptor
) {
return new SessionImpl(
connection,
this,
autoClose,
timestamp,
sessionLocalInterceptor == null ? interceptor : sessionLocalInterceptor,
settings.getDefaultEntityMode(),
settings.isFlushBeforeCompletionEnabled(),
settings.isAutoCloseSessionEnabled(),
settings.getConnectionReleaseMode()
);
}
最后,openSession调用了方法SessionImpl
SessionImpl(
final Connection connection,
final SessionFactoryImpl factory,
final boolean autoclose,
final long timestamp,
final Interceptor interceptor,
final EntityMode entityMode,
final boolean flushBeforeCompletionEnabled,
final boolean autoCloseSessionEnabled,
final ConnectionReleaseMode connectionReleaseMode) {
super( factory );
this.rootSession = null;
this.timestamp = timestamp;
this.entityMode = entityMode;
this.interceptor = interceptor;
this.listeners = factory.getEventListeners();
this.actionQueue = new ActionQueue( this );
this.persistenceContext = new StatefulPersistenceContext( this );
this.flushBeforeCompletionEnabled = flushBeforeCompletionEnabled;
this.autoCloseSessionEnabled = autoCloseSessionEnabled;
this.connectionReleaseMode = connectionReleaseMode;
this.jdbcContext = new JDBCContext( this, connection, interceptor );
loadQueryInfluencers = new LoadQueryInfluencers( factory );
if ( factory.getStatistics().isStatisticsEnabled() ) {
factory.getStatisticsImplementor().openSession();
}
if ( log.isDebugEnabled() ) {
log.debug( "opened session at timestamp: " + timestamp );
}
}
在
org.hibernate.stat.StatisticsImpl;<pre name="code" class="java">factory.getStatisticsImplementor().openSession();
我们看一下这个方法是什么呢?
<pre name="code" class="java">public synchronized void openSession() {
sessionOpenCount++;
}
没有忘记对session的数量进行自增。