摘要
在Spring下整合Hibernate时,关于sessionFactory的配置方式主要有两种,分别为注解配置方式,和xml配置方式,下面将对这两种配置方式进行介绍。
1. sessionFactory和数据库对应,有多少个数据库,就需要配置多少个sessionFactory;2. session相当于数据库连接,进行数据库的CRUD操作时,需要开启session,用完需要关闭session;
3. 配置sessionFactory,主要要配置如下三个方面:
3.1. 数据源配置;
3.2. Hibernate属性配置;
3.3. 映射文件配置;
(3.4 一般还需要进行事务配置)
关于sessionFactory的类型
Hibernate映射文件可以有两种方式:1. @注释 和 2.xml配置文件;
使用两种不同方式配置时,sessionFactory的类型不同,具体如下:
@注释方式:
org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
XML文件方式:
org.springframework.orm.hibernate3.LocalSessionFactoryBean
见程序:(applicationContext-xxx.xml)XML方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="connection.pool_size">100</prop>
<prop key="hibernate.jdbc.batch_size">100</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.default_schema">${hibernate.default_schema}</prop>
<省略...>
</props>
</property>
<property name="mappingDirectoryLocations">
<list>
<value>classpath:/config/hibernate-config-sql2000</value>
</list>
</property>
</bean>
</beans>
@注解方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<!-- 此处ORACLE与SQL数据库应该区别 -->
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<!-- <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> -->
<prop key="connection.pool_size">100</prop>
<prop key="hibernate.jdbc.batch_size">100</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.default_schema">${hibernate.default_schema}</prop>
<省略...>
</props>
</property>
<!--
<property name="mappingResources">
<list>
<value>hibernate-config/DistrictArea.hbm.xml</value>
</list>
</property>
-->
<property name="mappingDirectoryLocations">
<list>
<value>classpath:/config/hibernate-config</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>