配置示例
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" destroy-method="destroy">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.query.substitutions">true 'Y', false 'N'</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<!-- Hibernate Search index directory -->
<prop key="hibernate.search.default.indexBase">${app.search.index.basedir}</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
</props>
<!-- Turn batching off for better error messages under PostgreSQL -->
<!-- hibernate.jdbc.batch_size=0 -->
</property>
</bean>
源码分析
以上是利用Spring
读取Hibernate
的配置文件hibernate.cfg.xml
来构建sessessionFactory
.
我们都知道,Spring
容器在帮我们初始化一个类对象(此地方是LocalSessionFactoryBean
)后。
如果此类实现了InitializingBean
接口,那么该类会自动调用afterPropertiesSet
方法。
让我们看看LocalSessionFactoryBean
的afterPropertiesSet
源码
public void afterPropertiesSet() throws IOException {
LocalSessionFactoryBuilder sfb = new LocalSessionFactoryBuilder(this.dataSource, this.resourcePatternResolver);
if (this.configLocations != null) {
for (Resource resource : this.configLocations) {
// Load Hibernate configuration from given location.
sfb.configure(resource.getURL());
}
}
...//中间部分代码,已省略。
// Build SessionFactory instance.
this.configuration = sfb;
this.sessionFactory = buildSessionFactory(sfb);
}
LocalSessionFactoryBuilder
类继承自org.hibernate.cfg.Configuration
也就是说,初始化完LocalSessionFactoryBean
类后,
也就是把配置都读取后,Spring
开始调用Hibernate
的Configuration
里的configure
方法,
读取hibernate.cfg.xml
.并build
好sessessionFactory
放在Spring
容器中。