1、Spring整合Hibernate,整合什么?
① 由Spring的IOC容器管理Hibernate的SessionFactory
② 让Hibernate使用上Spring的声明式事务
2、整合步骤
① 加入Hibernate
i、jar包
ii、添加hibernate配置文件hibernate.cfg.xml文件
iii、编写了持久化对应的.hbm.xml文件
注:
可以使用Hibernate插件进行配置文件的自动生成,然后稍作修改即可(见参考资料)。
② 加入Spring
i、jar包
ii、加入Spring的配置文件
a、配置数据源
db.properties配置
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实例
hibernate.cfg.xml配置
<?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的基本属性 -->
<!-- 1、数据源需配置到Spring IOC容器中,所以此处无需配置数据源 -->
<!-- 2、关联的.hbm.xml也在IOC容器配置SessionFactory实例是再进行配置 -->
<!-- 3、可以配置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的声明式事务 -->
<!-- 1、配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 2、配置事务属性,需要事务管理器 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 3、配置事务切点,并将切点与事务属性关联起来 -->
<aop:config>
<aop:pointcut expression="execution(* com.lty.spring.hibernate.service.*.*(..))" id="txPointcut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
③ 整合
i、编写代码
3、代码测试
① 买isbn为“1001”的书时,为什么去掉applicationContext.xml切点与事务关联配置后,预期库存-1,余额不变无法测试?
<!-- 3、配置事务切点,并将切点与事务属性关联起来 -->
<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 事务的流程
* 1、在方法(spring事务)开始之前
* ① 获取session
* ② 将session和当前线程绑定,这样就可以在Dao中使用SessionFactory的
* getCurrentSession()方法来获取Session了
* ③ 开启事务
*
* 2、若方法正常结束,即未出现异常,则
* ① 提交事务
* ② 将Session与当前线程解除绑定
* ③ 关闭Session
*
* 3、若方法出现异常,则
* ① 回滚事务
* ② 将Session与当前线程解除绑定
* ③ 关闭Session
*
*/
@Override
public void purchase(String username, String isbn) {
int price = bookShopDao.findBookPriceByIsbn(isbn);
bookShopDao.updateBookStock(isbn);
bookShopDao.updateUserAccount(username, price);
}
}
② checkout方法测试事务的传播行为(允许买"1001"一本成功):
<!-- 2、配置事务属性,需要事务管理器 -->
<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>
4、附关键文件完整代码
① 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的声明式事务 -->
<!-- 1、配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 2、配置事务属性,需要事务管理器 -->
<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>
<!-- 3、配置事务切点,并将切点与事务属性关联起来 -->
<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"));
}
}
参考资料
1、如何在Eclipse上安装hibernate Tool?
来源:oschina
链接:https://my.oschina.net/u/3144678/blog/1554650