hibernate一些底层实现的解析

一、SessionFactory.openSession()

1、获取Connection

这里会通过调用hibernate的ConnectionProvider接口的getConnection()获取Connection,而实际执行的有三个类继承ConnectionProvider:

    1、DatasourceConnectionProviderImpl通过数据源获取:dataSource.getConnection();

    2、DriverManagerConnectionProviderImpl通过ConnectionCreator获取:connectionCreator.createConnection();

    3、UserSuppliedConnectionProviderImpl仅仅是抛出异常;

这里详细说明一下第一种:hibernate和各种连接池的联系是通过java的DateSource,hibernate使用DateSource的接口,各种连接池提供DateSource的实现类。而我们则是把该实现类定义为Bean。比如在tomcat.jdbc.pool中,dataSource.getConnection()这个方法实际上是通过连接池的ConnectionPool的ProxyClassConstructor.newInstance()获取Connection。

2、openSession()的实现代码(hibernate),简略:

package org.hibernate.internal;

import java.sql.Connection;

import org.hibernate.Interceptor;
import org.hibernate.Session;
import org.hibernate.SessionEventListener;
import org.hibernate.engine.spi.SessionBuilderImplementor;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionOwner;
import org.hibernate.internal.SessionImpl;

public final class SessionFactoryImpl implements SessionFactoryImplementor {
	
	static class SessionBuilderImpl implements SessionBuilderImplementor {
		
		private final SessionFactoryImpl sessionFactory;
		private Connection connection;
		
		@Override
		public Session openSession() {
			final SessionImpl session = new SessionImpl(
					connection,
					sessionFactory,
					sessionOwner,
					getTransactionCoordinator(),
					getTransactionCompletionProcesses(),
					autoJoinTransactions,
					sessionFactory.settings.getRegionFactory().nextTimestamp(),
					interceptor,
					flushBeforeCompletion,
					autoClose,
					connectionReleaseMode,
					tenantIdentifier
			);

			for ( SessionEventListener listener : listeners ) {
				session.getEventListenerManager().addListener( listener );
			}

			return session;
		}
	}

}
因此有时候我们说:Hibernate session就是java.sql.Connection的一层高级封装,一个session对应了一个Connection。




你可能感兴趣的:(hibernate一些底层实现的解析)