在Hibernate中,SessionFactory是一個重量級對象,建立與初始化會耗費大量的資源,應該減小對象的建立次數,而且SessionFactory線程安全,能夠採用單例模式,若是將對象的建立任務交給Spring容器就解決了這個問題。spring
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>
Spring爲兼容Hibernate提供的事務管理器爲HibernateTransactionManager:數據庫
<bean id="transactionManager"class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean>
Spring爲不一樣的操做數據庫的方式提供了不一樣的數據源,JDBC與Mybatis共享DataSourceTransactionManager。express
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="實體所在的包"/>