① 由Spring的IOC容器管理Hibernate的SessionFactory
② 讓Hibernate使用上Spring的聲明式事務html
① 加入Hibernate
i、jar包
ii、添加hibernate配置文件hibernate.cfg.xml文件
iii、編寫了持久化對應的.hbm.xml文件java
注:mysql
可使用Hibernate插件進行配置文件的自動生成,而後稍做修改便可(見參考資料)。
② 加入Springgit
i、jar包
ii、加入Spring的配置文件spring
a、配置數據源sql
db.properties配置express
jdbc.user=root jdbc.password=liuhao jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl=jdbc:mysql:///spring7 jdbc.initPoolSize=5 jdbc.maxPoolSize=10
applicationContext.xml配置緩存
<!-- 配置數據源 --> <context:property-placeholder location="classpath:db.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean>
b、配置Hibernate的SessionFactory實例session
hibernate.cfg.xml配置app
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 配置hibernate的基本屬性 --> <!-- 一、數據源需配置到Spring IOC容器中,因此此處無需配置數據源 --> <!-- 二、關聯的.hbm.xml也在IOC容器配置SessionFactory實例是再進行配置 --> <!-- 三、能夠配置Hibernate的基本屬性,如方言、SQL顯示及格式化,生成數據表的策略及二級緩存等 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 配置Hibernate的二級緩存屬性相關 --> </session-factory> </hibernate-configuration>
applicationContext.xml配置
<!-- 配置Hibernate的SessionFactory實例:經過Spring提供的LocalSessionFactoryBean進行配置 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 配置數據源屬性 --> <property name="dataSource" ref="dataSource"></property> <!-- 配置hibernate配置文件的位置及名稱 --> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <!-- 配置hibernate映射文件的位置及名稱,可使用通配符 --> <property name="mappingLocations" value="classpath:com/lty/spring/hibernate/entity/*.hbm.xml"></property> </bean>
c、配置Spring的聲明式事務(applicationContext.xml配置)
<!-- 配置Spring的聲明式事務 --> <!-- 一、配置事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 二、配置事務屬性,須要事務管理器 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 三、配置事務切點,並將切點與事務屬性關聯起來 --> <aop:config> <aop:pointcut expression="execution(* com.lty.spring.hibernate.service.*.*(..))" id="txPointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config>
③ 整合
i、編寫代碼
① 買isbn爲「1001」的書時,爲何去掉applicationContext.xml切點與事務關聯配置後,預期庫存-1,餘額不變沒法測試?
<!-- 三、配置事務切點,並將切點與事務屬性關聯起來 --> <aop:config> <aop:pointcut expression="execution(* com.lty.spring.hibernate.service.*.*(..))" id="txPointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config>
@Test public void testBookShopService(){ bookShopService.purchase("aa", "1001"); }
緣由:
這是由於去掉這部分配置後,session將沒法獲取(Hibernate與Spring整合的Session是創建在Spring事務基礎之上的):
org.hibernate.HibernateException: No Session found for current thread at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106) at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:988) at com.lty.spring.hibernate.dao.impl.BookShopDaoImpl.getSession(BookShopDaoImpl.java:27) at com.lty.spring.hibernate.dao.impl.BookShopDaoImpl.findBookPriceByIsbn(BookShopDaoImpl.java:33) at com.lty.spring.hibernate.service.impl.BookShopServiceImpl.purchase(BookShopServiceImpl.java:37) at com.lty.spring.hibernate.test.SpringHibernateTest.testBookShopService(SpringHibernateTest.java:36) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
沒法測試詳細緣由說明:
package com.lty.spring.hibernate.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.lty.spring.hibernate.dao.BookShopDao; import com.lty.spring.hibernate.service.BookShopService; @Service public class BookShopServiceImpl implements BookShopService { @Autowired private BookShopDao bookShopDao; /*** * * Spring Hibernate 事務的流程 * 一、在方法(spring事務)開始以前 * ① 獲取session * ② 將session和當前線程綁定,這樣就能夠在Dao中使用SessionFactory的 * getCurrentSession()方法來獲取Session了 * ③ 開啓事務 * * 二、若方法正常結束,即未出現異常,則 * ① 提交事務 * ② 將Session與當前線程解除綁定 * ③ 關閉Session * * 三、若方法出現異常,則 * ① 回滾事務 * ② 將Session與當前線程解除綁定 * ③ 關閉Session * */ @Override public void purchase(String username, String isbn) { int price = bookShopDao.findBookPriceByIsbn(isbn); bookShopDao.updateBookStock(isbn); bookShopDao.updateUserAccount(username, price); } }
② checkout方法測試事務的傳播行爲(容許買"1001"一本成功):
<!-- 二、配置事務屬性,須要事務管理器 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="purchase" propagation="REQUIRES_NEW"/> <tx:method name="*"/> </tx:attributes> </tx:advice>
① applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <context:component-scan base-package="com.lty.spring.hibernate"></context:component-scan> <!-- 配置數據源 --> <context:property-placeholder location="classpath:db.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean> <!-- 配置Hibernate的SessionFactory實例:經過Spring提供的LocalSessionFactoryBean進行配置 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 配置數據源屬性 --> <property name="dataSource" ref="dataSource"></property> <!-- 配置hibernate配置文件的位置及名稱 --> <!-- <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> --> <!-- 使用hibernateProperties屬性來配置Hibernate原生的屬性 (不推薦)--> <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> </props> </property> <!-- 配置hibernate映射文件的位置及名稱,可使用通配符 --> <property name="mappingLocations" value="classpath:com/lty/spring/hibernate/entity/*.hbm.xml"></property> </bean> <!-- 配置Spring的聲明式事務 --> <!-- 一、配置事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 二、配置事務屬性,須要事務管理器 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="purchase" propagation="REQUIRES_NEW"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 三、配置事務切點,並將切點與事務屬性關聯起來 --> <aop:config> <aop:pointcut expression="execution(* com.lty.spring.hibernate.service.*.*(..))" id="txPointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config> </beans>
② SpringHibernateTest
package com.lty.spring.hibernate.test; import java.sql.SQLException; import java.util.Arrays; import javax.sql.DataSource; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.lty.spring.hibernate.service.BookShopService; import com.lty.spring.hibernate.service.Cashier; public class SpringHibernateTest { private ApplicationContext ctx = null; private BookShopService bookShopService = null; private Cashier cashier = null; { ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); bookShopService = ctx.getBean(BookShopService.class); cashier = ctx.getBean(Cashier.class); } @Test public void testDataSource() throws SQLException{ DataSource dataSource = ctx.getBean(DataSource.class); System.out.println(dataSource.getConnection()); } @Test public void testBookShopService(){ bookShopService.purchase("aa", "1001"); } @Test public void testCashier(){ cashier.checkout("aa", Arrays.asList("1001","1002")); } }