Spring與Hibernate整合的相關問題和解決方案(整合方案一:dataSource交給Spring來管理)
整合的關鍵點:
- Hibernate的SessionFactory物件交給Spring去建立;
- Hibernate的事務交給Spring的宣告式事務管理;(Hibernate的操作是基於事務的操作);
整合步驟:
- 配置資料來源(採用C3P0連線池)
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
<property name="initialPoolSize" value="3"></property>
<property name="maxPoolSize" value="10"></property>
<property name="maxStatements" value="100"></property>
<property name="acquireIncrement" value="2"></property>
</bean>
2.將SessionFactory的建立交給Spring來完成(SessionFactory的建立時由config.configure().buildSessionFactory()方法來獲取的,故需要對hibernate.cfg.xml進行配置載入,而不是採用程式碼的形式進行載入)究其根源還是要獲取資料庫的連線來對資料庫進行操作,所以要配置dataSoure屬性的值;
<!-- 建立SessionFactory物件,, -->
<bean id="sessionfactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 把hibernate配置檔案注入給了LocalSessionFactoryBean,也可以把一個數據源dataSource注入給它)所以為了完成spring的依賴注入,Spring提供了LocalSessionFactoryBean這個類.從而建立SessionFactory物件 -->
<property name="configLocation" value="hibernate.cfg.xml"></property><property name="dataSource" ref="datasource"></property>
</bean>
注:如果缺少datasource屬性的配置,會產生如下錯誤:
3:配置事務管理器類、事務增強(攔截到方法後如何管理事務)、配置AOP管理
<!-- 配置事務管理器類 用Hibernate技術連線時,事物管理器類為HibernateTransactionManager,且傳入的引數為sessionFactory->
<bean id="tManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionfactory"></property><!-- <property name="dataSource" ref="datasource"></property> -->
</bean>
注:用JDBC技術連線時,事務管理器類為DataSourceTransactionManager;
<!--配置JdbcTemplate ,該類中維護了一個dataSource變數 -->
<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="datasource"></property>
</bean>
<tx:advice id="tx" transaction-manager="tManager">
<tx:attributes>
<tx:method name="save*" read-only="false"/>
</tx:attributes>
</tx:advice>
<!-- 配置AOP -->
<aop:config>
<aop:pointcut expression="execution(* xzx.service.*.*(..))" id="pcut"/>
<aop:advisor advice-ref="tx" pointcut-ref="pcut"/>
</aop:config>
注意事項:在Spring和Hibernate整合時,session的獲取建議用getCurrentSession();且不用在Hibernate.cfg.xml中進行配置以執行緒的方式獲取session:<property name="hibernate.current_session_context_class">thread</property> 否則會報錯。