Welcome 微信登录

首页 / 软件开发 / JAVA / Spring源代码解析(八):Spring驱动Hibernate的实现

Spring源代码解析(八):Spring驱动Hibernate的实现2011-03-29 javaeye jiwenkeO/R工具出现之后,简化了许多复杂的信息持久化的开发。Spring应用开发者可以通过 Spring提供的O/R方案更方便的使用各种持久化工具,比如Hibernate;下面我们就 Spring+Hibernate中的Spring实现做一个简单的剖析。

Spring对Hinberanate的配置是通过LocalSessionFactoryBean来完成的,这是一个工 厂Bean的实现,在基类AbstractSessionFactoryBean中:

Java代码

/**
* 这是FactoryBean需要实现的接口方法,直接取得当前的sessionFactory的 值
*/
public Object getObject() {
return this.sessionFactory;
}

这个值在afterPropertySet中定义:

Java代码

public void afterPropertiesSet() throws Exception {
//这个buildSessionFactory是通过配置信息得到SessionFactory的地方
SessionFactory rawSf = buildSessionFactory();
//这里使用了Proxy方法插入对getCurrentSession的拦截,得到和事务相关 的session
this.sessionFactory = wrapSessionFactoryIfNecessary(rawSf);
}

我们先看看SessionFactory是怎样创建的,这个方法很长,包含了创建Hibernate的 SessionFactory的详尽步骤:

Java代码

protected SessionFactory buildSessionFactory() throws Exception {
SessionFactory sf = null;
// Create Configuration instance.
Configuration config = newConfiguration();
//这里配置数据源,事务管理器,LobHander到Holder中,这个Holder是一个 ThreadLocal变量,这样这些资源就和线程绑定了
if (this.dataSource != null) {
// Make given DataSource available for SessionFactory configuration.
configTimeDataSourceHolder.set(this.dataSource);
}
if (this.jtaTransactionManager != null) {
// Make Spring-provided JTA TransactionManager available.
configTimeTransactionManagerHolder.set (this.jtaTransactionManager);
}
if (this.lobHandler != null) {
// Make given LobHandler available for SessionFactory configuration.
// Do early because because mapping resource might refer to custom types.
configTimeLobHandlerHolder.set(this.lobHandler);
}
//这里是使用Hibernate的各个属性的配置,这里使用了Configuration类来 抽象这些数据
try {
// Set connection release mode "on_close" as default.
// This was the case for Hibernate 3.0; Hibernate 3.1 changed
// it to "auto" (i.e. "after_statement" or "after_transaction").
// However, for Spring"s resource management (in particular for
// HibernateTransactionManager), "on_close" is the better default.
config.setProperty(Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.ON_CLOSE.toString());
if (!isExposeTransactionAwareSessionFactory()) {
// Not exposing a SessionFactory proxy with transaction- aware
// getCurrentSession() method -> set Hibernate 3.1 CurrentSessionContext
// implementation instead, providing the Spring-managed Session that way.
// Can be overridden by a custom value for corresponding Hibernate property.
config.setProperty (Environment.CURRENT_SESSION_CONTEXT_CLASS,
"org.springframework.orm.hibernate3.SpringSessionContext");
}
if (this.entityInterceptor != null) {
// Set given entity interceptor at SessionFactory level.
config.setInterceptor(this.entityInterceptor);
}
if (this.namingStrategy != null) {
// Pass given naming strategy to Hibernate Configuration.
config.setNamingStrategy(this.namingStrategy);
}
if (this.typeDefinitions != null) {
// Register specified Hibernate type definitions.
Mappings mappings = config.createMappings();
for (int i = 0; i < this.typeDefinitions.length; i++) {
TypeDefinitionBean typeDef = this.typeDefinitions [i];
mappings.addTypeDef(typeDef.getTypeName(), typeDef.getTypeClass(), typeDef.getParameters());
}
}
if (this.filterDefinitions != null) {
// Register specified Hibernate FilterDefinitions.
for (int i = 0; i < this.filterDefinitions.length; i++) {
config.addFilterDefinition(this.filterDefinitions [i]);
}
}
if (this.configLocations != null) {
for (int i = 0; i < this.configLocations.length; i++) {
// Load Hibernate configuration from given location.
config.configure(this.configLocations[i].getURL());
}
}
if (this.hibernateProperties != null) {
// Add given Hibernate properties to Configuration.
config.addProperties(this.hibernateProperties);
}
if (this.dataSource != null) {
boolean actuallyTransactionAware =
(this.useTransactionAwareDataSource || this.dataSource instanceof TransactionAwareDataSourceProxy);
// Set Spring-provided DataSource as Hibernate ConnectionProvider.
config.setProperty(Environment.CONNECTION_PROVIDER,
actuallyTransactionAware ?
TransactionAwareDataSourceConnectionProvider.class.getName() :
LocalDataSourceConnectionProvider.class.getName ());
}
if (this.jtaTransactionManager != null) {
// Set Spring-provided JTA TransactionManager as Hibernate property.
config.setProperty(
Environment.TRANSACTION_MANAGER_STRATEGY, LocalTransactionManagerLookup.class.getName());
}
if (this.mappingLocations != null) {
// Register given Hibernate mapping definitions, contained in resource files.
for (int i = 0; i < this.mappingLocations.length; i++) {
config.addInputStream(this.mappingLocations [i].getInputStream());
}
}
if (this.cacheableMappingLocations != null) {
// Register given cacheable Hibernate mapping definitions, read from the file system.
for (int i = 0; i < this.cacheableMappingLocations.length; i++) {
config.addCacheableFile(this.cacheableMappingLocations [i].getFile());
}
}
if (this.mappingJarLocations != null) {
// Register given Hibernate mapping definitions, contained in jar files.
for (int i = 0; i < this.mappingJarLocations.length; i++) {
Resource resource = this.mappingJarLocations[i];
config.addJar(resource.getFile());
}
}
if (this.mappingDirectoryLocations != null) {
// Register all Hibernate mapping definitions in the given directories.
for (int i = 0; i < this.mappingDirectoryLocations.length; i++) {
File file = this.mappingDirectoryLocations[i].getFile ();
if (!file.isDirectory()) {
throw new IllegalArgumentException(
"Mapping directory location [" + this.mappingDirectoryLocations[i] +
"] does not denote a directory");
}
config.addDirectory(file);
}
}
if (this.entityCacheStrategies != null) {
// Register cache strategies for mapped entities.
for (Enumeration classNames = this.entityCacheStrategies.propertyNames(); classNames.hasMoreElements();) {
String className = (String) classNames.nextElement ();
String[] strategyAndRegion =
StringUtils.commaDelimitedListToStringArray (this.entityCacheStrategies.getProperty(className));
if (strategyAndRegion.length > 1) {
config.setCacheConcurrencyStrategy(className, strategyAndRegion[0], strategyAndRegion[1]);
}
else if (strategyAndRegion.length > 0) {
config.setCacheConcurrencyStrategy(className, strategyAndRegion[0]);
}
}
}
if (this.collectionCacheStrategies != null) {
// Register cache strategies for mapped collections.
for (Enumeration collRoles = this.collectionCacheStrategies.propertyNames(); collRoles.hasMoreElements();) {
String collRole = (String) collRoles.nextElement();
String[] strategyAndRegion =
StringUtils.commaDelimitedListToStringArray (this.collectionCacheStrategies.getProperty(collRole));
if (strategyAndRegion.length > 1) {
config.setCollectionCacheConcurrencyStrategy (collRole, strategyAndRegion[0], strategyAndRegion[1]);
}
else if (strategyAndRegion.length > 0) {
config.setCollectionCacheConcurrencyStrategy (collRole, strategyAndRegion[0]);
}
}
}
if (this.eventListeners != null) {
// Register specified Hibernate event listeners.
for (Iterator it = this.eventListeners.entrySet().iterator (); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Assert.isTrue(entry.getKey() instanceof String, "Event listener key needs to be of type String");
String listenerType = (String) entry.getKey();
Object listenerObject = entry.getValue();
if (listenerObject instanceof Collection) {
Collection listeners = (Collection) listenerObject;
EventListeners listenerRegistry = config.getEventListeners();
Object[] listenerArray =
(Object[]) Array.newInstance (listenerRegistry.getListenerClassFor(listenerType), listeners.size());
listenerArray = listeners.toArray (listenerArray);
config.setListeners(listenerType, listenerArray);
}
else {
config.setListener(listenerType, listenerObject);
}
}
}
// Perform custom post-processing in subclasses.
postProcessConfiguration(config);
// 这里是根据Configuration配置创建SessionFactory的地方
logger.info("Building new Hibernate SessionFactory");
this.configuration = config;
sf = newSessionFactory(config);
}
//最后把和线程绑定的资源清空
finally {
if (this.dataSource != null) {
// Reset DataSource holder.
configTimeDataSourceHolder.set(null);
}
if (this.jtaTransactionManager != null) {
// Reset TransactionManager holder.
configTimeTransactionManagerHolder.set(null);
}
if (this.lobHandler != null) {
// Reset LobHandler holder.
configTimeLobHandlerHolder.set(null);
}
}
// Execute schema update if requested.
if (this.schemaUpdate) {
updateDatabaseSchema();
}
return sf;
}