① 由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")); } }