上一篇中:
Hibernate源代碼分析(一):設(shè)計(jì)屬于我的SessionFactory和ConnectionProvider 分析到了SessionFactoryImpl.openSession()方法,該方法將其
職責(zé)委托給了SessionImpl,打開org.hibernate.impl.SessionImpl.java,看看實(shí)現(xiàn)代碼:
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
}
我們關(guān)注的就是數(shù)據(jù)庫連接,重點(diǎn)關(guān)注第22行,在該行將Connection對象傳遞給了JDBCContext,通過觀察前面的代碼我們可以發(fā)現(xiàn),JTASessionContext.buildOrObtainSession() 方法傳遞的Connection對象為null,這個可以說,Connection對象的獲得將由
ConnectionProvider接口的實(shí)現(xiàn)類來完成。
接下來看看JDBCContent類的構(gòu)造函數(shù),跳轉(zhuǎn)到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
}
這段程序代碼里創(chuàng)建了一個新的對象connectionManager,我們跟蹤一下org.hibernate.jdbc.ConnectionManager.java,在這個文件里可以
發(fā)現(xiàn)一個方法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
}
現(xiàn)在,最有價值的發(fā)現(xiàn)出來了,在第8行,這里就是從緩沖池獲得數(shù)據(jù)庫連接的代碼。
接下來我們可以設(shè)計(jì)實(shí)現(xiàn)ConnectionProvider的具體類了。