Spring與Hibernate整合

一 概述

1.整合目的

在Hibernate中,SessionFactory是一個重量級對象,建立與初始化會耗費大量的資源,應該減小對象的建立次數,而且SessionFactory線程安全,能夠採用單例模式,若是將對象的建立任務交給Spring容器就解決了這個問題。spring

二 實現

1.配置SessionFactory建立類

Spring提供了LocalSessionFactoryBean負責建立SessionFactory對象:sql

<bean id="sessionFactory"class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="c3p0" />
    <property name="hibernateProperties">
       <props>
           <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
           <prop key="hibernate.show_sql">true</prop>
           <prop key="hibernate.format_sql">true</prop>
           <prop key="hibernate.hbm2ddl.auto">update</prop>
           <prop key="hibernate.current_session_context_class">
org.springframework.orm.hibernate5.SpringSessionContext</prop> </props> </property> <property name="mappingDirectoryLocations" value="com/spring_hibernate/integration/demo01" /> </bean>
  • mappingDirectoryLocations:配置映射文件,只須要指明映射文件的根路徑便可,系統會自動加載此路徑下的映射文件。
  • current_session_context_class:用來指定Session對象所處的上下文環境,即Session的建立者,Spring與Hibernate整合之後,Session對象就由Spring容器建立與管理。

2.配置事務管理器

Spring爲兼容Hibernate提供的事務管理器爲HibernateTransactionManager:數據庫

<bean id="transactionManager"class="org.springframework.orm.hibernate5.HibernateTransactionManager">
      <property name="sessionFactory" ref="sessionFactory" />
</bean>

Spring爲不一樣的操做數據庫的方式提供了不一樣的數據源,JDBC與Mybatis共享DataSourceTransactionManager。express

3.配置事務

Spring提供了兩種事務,一種基於Spring自身AOP的事務,一種基於AspectJ的事務,因爲後者比前者簡單方便,採用後者爲Dao服務層配置事務:安全

<tx:advice id="advice" transaction-manager="transactionManager">
   <tx:attributes>
      <tx:method name="find*" isolation="DEFAULT" propagation="REQUIRED"read-only="true" />
      <tx:method name="modify*" isolation="DEFAULT" propagation="REQUIRED"rollback-for="exception" />
      <tx:method name="add*" isolation="DEFAULT" propagation="REQUIRED"rollback-for="exception" />
      <tx:method name="remove*" isolation="DEFAULT" propagation="REQUIRED"rollback-for="exception" />
   </tx:attributes>
</tx:advice>
<aop:config>
   <aop:pointcut id="p01" expression="execution(* *..demo01.*.*(..))" />
   <aop:advisor advice-ref="advice" pointcut-ref="p01" />
</aop:config>

三 註解

當Hibernate的實體類採用註解註冊時,映射文件被取代,所以須要在Spring配置文件中修改映射關係的設定方式,修改成:session

<property name="packagesToScan"value="實體所在的包"/>
相關文章
相關標籤/搜索