上一篇中:
Hibernate源代碼分析(一):設計屬于我的SessionFactory和ConnectionProvider 分析到了SessionFactoryImpl.openSession()方法,該方法將其
職責委托給了SessionImpl,打開org.hibernate.impl.SessionImpl.java,看看實現代碼:
1
SessionImpl(
2
final Connection connection,
3
final SessionFactoryImpl factory,
4
final boolean autoclose,
5
final long timestamp,
6
final Interceptor interceptor,
7
final EntityMode entityMode,
8
final boolean flushBeforeCompletionEnabled,
9
final boolean autoCloseSessionEnabled,
10
final ConnectionReleaseMode connectionReleaseMode)
{
11
super( factory );
12
this.rootSession = null;
13
this.timestamp = timestamp;
14
this.entityMode = entityMode;
15
this.interceptor = interceptor;
16
this.listeners = factory.getEventListeners();
17
this.actionQueue = new ActionQueue( this );
18
this.persistenceContext = new StatefulPersistenceContext( this );
19
this.flushBeforeCompletionEnabled = flushBeforeCompletionEnabled;
20
this.autoCloseSessionEnabled = autoCloseSessionEnabled;
21
this.connectionReleaseMode = connectionReleaseMode;
22
this.jdbcContext = new JDBCContext( this, connection, interceptor );
23
24
if ( factory.getStatistics().isStatisticsEnabled() )
{
25
factory.getStatisticsImplementor().openSession();
26
}
27
28
if ( log.isDebugEnabled() )
{
29
log.debug( "opened session at timestamp: " + timestamp );
30
}
31
}
我們關注的就是數據庫連接,重點關注第22行,在該行將Connection對象傳遞給了JDBCContext,通過觀察前面的代碼我們可以發現,JTASessionContext.buildOrObtainSession() 方法傳遞的Connection對象為null,這個可以說,Connection對象的獲得將由
ConnectionProvider接口的實現類來完成。
接下來看看JDBCContent類的構造函數,跳轉到org.hibernate.jdbc.JDBCContent.java,程序代碼如下:
1
public JDBCContext(Context owner, Connection connection, Interceptor interceptor)
{
2
this.owner = owner;
3
this.connectionManager = new ConnectionManager(
4
owner.getFactory(),
5
this,
6
owner.getConnectionReleaseMode(),
7
connection,
8
interceptor
9
);
10
11
final boolean registerSynchronization = owner.isAutoCloseSessionEnabled()
12
|| owner.isFlushBeforeCompletionEnabled()
13
|| owner.getConnectionReleaseMode() == ConnectionReleaseMode.AFTER_TRANSACTION;
14
if ( registerSynchronization )
{
15
registerSynchronizationIfPossible();
16
}
17
}
這段程序代碼里創建了一個新的對象connectionManager,我們跟蹤一下org.hibernate.jdbc.ConnectionManager.java,在這個文件里可以
發現一個方法openConnection(),代碼如下:
1
private void openConnection() throws HibernateException
{
2
if ( connection != null )
{
3
return;
4
}
5
6
log.debug("opening JDBC connection");
7
try
{
8
connection = factory.getConnectionProvider().getConnection();
9
}
10
catch (SQLException sqle)
{
11
throw JDBCExceptionHelper.convert(
12
factory.getSQLExceptionConverter(),
13
sqle,
14
"Cannot open connection"
15
);
16
}
17
18
callback.connectionOpened(); // register synch; stats.connect()
19
}
現在,最有價值的發現出來了,在第8行,這里就是從緩沖池獲得數據庫連接的代碼。
接下來我們可以設計實現ConnectionProvider的具體類了。