Spring 事务配置

本文转自:http://www.cnblogs.com/leiOOlei/p/3725911.html#s1

要了解事务配置的所有方法,请看一下《Spring事务配置的5种方法

本文介绍两种配置方法:

 

以下所使用环境为Spring4.0.3、Hibernate4.3.5

 

一、      XML,使用tx标签配置拦截器实现事务


Entity类User.java,持久化类,对应数据库表user

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.lei.demo.entity;  
  2.   
  3. import javax.persistence.*;  
  4.   
  5. @Entity(name="users")  
  6. public class Users {  
  7.       
  8.     public Users(){  
  9.         super();  
  10.     }  
  11.       
  12.     @Id  
  13.     @GeneratedValue(strategy=GenerationType.AUTO)  
  14.     @Column(name="id")  
  15.     private Integer id;  
  16.       
  17.     @Column(name="user_name",length=32)  
  18.     private String user_name;  
  19.       
  20.     @Column(name="age")  
  21.     private Integer age;  
  22.       
  23.     @Column(name="nice_name",length=32)  
  24.     private String nice_name;  
  25.       
  26.     //属性实现......  
  27.   
  28. }  

UserDAO.javar,user的一些操作,其中属性sessionFactory应该由Spring注入,如下:


[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.lei.demo.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.annotation.Resource;  
  6.   
  7. import org.hibernate.Query;  
  8. import org.hibernate.Session;  
  9. import org.hibernate.SessionFactory;  
  10. import org.springframework.stereotype.Repository;  
  11.   
  12. import com.lei.demo.entity.Users;  
  13.   
  14. public class UsersDAO {  
  15.     private SessionFactory sessionFactory;  
  16.   
  17.     public void setSessionFactory(SessionFactory sessionFactory) {  
  18.         this.sessionFactory = sessionFactory;  
  19.     }  
  20.   
  21.     public SessionFactory getSessionFactory() {  
  22.         return sessionFactory;  
  23.     }  
  24.   
  25.     public List<Users> getAllUser(){  
  26.         String hsql="from users";  
  27.         Session session = sessionFactory.getCurrentSession();  
  28.         Query query = session.createQuery(hsql);  
  29.           
  30.         return query.list();  
  31.     }  
  32. }  

UserService.java,业务实现类,如下


[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.lei.demo.service;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Service;  
  6. import org.springframework.transaction.annotation.Isolation;  
  7. import org.springframework.transaction.annotation.Propagation;  
  8. import org.springframework.transaction.annotation.Transactional;  
  9.   
  10. import com.lei.demo.dao.*;  
  11.   
  12. public class UserService {  
  13.     private UsersDAO userDao;  
  14.       
  15.     public int userCount(){  
  16.         return userDao.getAllUser().size();  
  17.     }  
  18.   
  19.     public UsersDAO getUserDao() {  
  20.         return userDao;  
  21.     }  
  22.   
  23.     public void setUserDao(UsersDAO userDao) {  
  24.         this.userDao = userDao;  
  25.     }  
  26.   
  27. }  

首先看一下xml配置,spring-hibernate.xml如下:


[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xmlns:aop="http://www.springframework.org/schema/aop"  
  7.     xsi:schemaLocation="  
  8.         http://www.springframework.org/schema/beans       
  9.         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
  10.         http://www.springframework.org/schema/context  
  11.         http://www.springframework.org/schema/context/spring-context-4.0.xsd  
  12.         http://www.springframework.org/schema/aop  
  13.         http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
  14.         http://www.springframework.org/schema/tx  
  15.         http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
  16.         ">  
  17.   
  18.     <!-- Hibernate4 -->  
  19.     <!-- 加载资源文件  其中包含变量信息,必须在Spring配置文件的最前面加载,即第一个加载-->  
  20.     <context:property-placeholder location="classpath:persistence-mysql.properties" />  
  21.       
  22.     <bean id="sessionFactory"   
  23.         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
  24.         <property name="dataSource" ref="dataSource" />  
  25.         <property name="packagesToScan">  
  26.             <list>  
  27.                 <!-- 可以加多个包 -->  
  28.                 <value>com.lei.demo.entity</value>  
  29.             </list>  
  30.         </property>  
  31.         <property name="hibernateProperties">  
  32.             <props>  
  33.                 <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>  
  34.                 <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
  35.                 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
  36.                 <!--  <prop key="hibernate.current_session_context_class">thread</prop> -->   
  37.             </props>  
  38.         </property>  
  39.     </bean>  
  40.       
  41.     <!-- 数据库映射 -->  
  42.     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  43.       <property name="driverClassName" value="${jdbc.driverClassName}" />  
  44.       <property name="url" value="${jdbc.url}" />  
  45.       <property name="username" value="${jdbc.user}" />  
  46.       <property name="password" value="${jdbc.pass}" />  
  47.    </bean>  
  48.      
  49.     <!-- 配置Hibernate事务管理器 -->  
  50.     <bean id="transactionManager"  
  51.         class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
  52.       <property name="sessionFactory" ref="sessionFactory" />  
  53.    </bean>  
  54.      
  55.    <!-- 配置事务异常封装 -->  
  56.    <bean id="persistenceExceptionTranslationPostProcessor"   
  57.        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />  
  58.      
  59.    <!--  声明式容器事务管理 ,transaction-manager指定事务管理器为transactionManager -->  
  60.     <tx:advice id="txAdvice" transaction-manager="transactionManager">  
  61.         <tx:attributes>  
  62.             <tx:method name="add*" propagation="REQUIRED" />  
  63.             <tx:method name="get*" propagation="REQUIRED" />  
  64.             <tx:method name="*" read-only="true" />  
  65.         </tx:attributes>  
  66.     </tx:advice>  
  67.       
  68.     <aop:config expose-proxy="true">  
  69.         <!-- 只对业务逻辑层实施事务 -->  
  70.         <aop:pointcut id="txPointcut" expression="execution(* com.lei.demo.service..*.*(..))" />  
  71.         <!-- Advisor定义,切入点和通知分别为txPointcut、txAdvice -->  
  72.         <aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/>  
  73.     </aop:config>  
  74.       
  75. </beans>  

其中主要配置中是tx:adviceaop:config两个配置节,以Spring AOP的方式实现事务管理。

tx:advice配置了事务的管理者是transactionManager,同时tx:method也规定了如果方法名匹配“add*”和“get*”方法时使用事务,propagation是设定事务的传播级别。除了“add*”和“get*”方法,其他的方法的事务是只读的(典型地,对于只执行查询的事务你会将该属性设为true,如果出现了更新、插入或是删除语句时只读事务就会失败)

aop:config指定了一个aop:pointcut去引用上边的advice。

这样就通过AOP的拦截机制实现了事务,当然你还要用Spring的方式自己配置UserDAO和UserService。

 

二、      Annotation方式


第一步,首先看一下web.xml,如下:


[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:web="http://java.sun.com/xml/ns/javaee"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"   
  7.         id="WebApp_ID" version="3.0">  
  8.   <display-name>Archetype Created Web Application</display-name>  
  9.   <context-param>  
  10.     <param-name>contextConfigLocation</param-name>  
  11.     <param-value>classpath:/spring-*.xml</param-value>  
  12.   </context-param>  
  13.   <listener>  
  14.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  15.   </listener>  
  16.   <servlet>  
  17.     <servlet-name>lei-dispatcher</servlet-name>  
  18.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  19.     <init-param>  
  20.       <param-name>contextConfigLocation</param-name>  
  21.       <param-value>classpath:/lei-dispatcher-servlet.xml</param-value>  
  22.     </init-param>  
  23.     <load-on-startup>1</load-on-startup>  
  24.   </servlet>  
  25.   <servlet-mapping>  
  26.     <servlet-name>lei-dispatcher</servlet-name>  
  27.     <url-pattern>/</url-pattern>  
  28.   </servlet-mapping>  
  29. </web-app>  

第二步,spring-hibernate配置,见以下spring-hibernate.xml配置


[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xmlns:aop="http://www.springframework.org/schema/aop"  
  7.     xsi:schemaLocation="  
  8.         http://www.springframework.org/schema/beans       
  9.         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
  10.         http://www.springframework.org/schema/context  
  11.         http://www.springframework.org/schema/context/spring-context-4.0.xsd  
  12.         http://www.springframework.org/schema/aop  
  13.         http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
  14.         http://www.springframework.org/schema/tx  
  15.         http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
  16.         ">  
  17.   
  18.     <!-- Hibernate4 -->  
  19.     <!-- 加载资源文件  其中包含变量信息,必须在Spring配置文件的最前面加载,即第一个加载-->  
  20.     <context:property-placeholder location="classpath:persistence-mysql.properties" />  
  21.       
  22.     <bean id="sessionFactory"   
  23.         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
  24.         <property name="dataSource" ref="dataSource" />  
  25.         <property name="packagesToScan">  
  26.             <list>  
  27.                 <!-- 可以加多个包 -->  
  28.                 <value>com.lei.demo.entity</value>  
  29.             </list>  
  30.         </property>  
  31.         <property name="hibernateProperties">  
  32.             <props>  
  33.                 <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>  
  34.                 <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
  35.                 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
  36.                 <!--  <prop key="hibernate.current_session_context_class">thread</prop> -->   
  37.             </props>  
  38.         </property>  
  39.     </bean>  
  40.       
  41.     <!-- 数据库映射 -->  
  42.     <!--  class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" -->  
  43.     <!--  class="org.springframework.jdbc.datasource.DriverManagerDataSource" -->  
  44.     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  45.       <property name="driverClassName" value="${jdbc.driverClassName}" />  
  46.       <property name="url" value="${jdbc.url}" />  
  47.       <property name="username" value="${jdbc.user}" />  
  48.       <property name="password" value="${jdbc.pass}" />  
  49.    </bean>  
  50.      
  51.     <!-- 配置Hibernate事务管理器 -->  
  52.     <bean id="transactionManager"  
  53.         class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
  54.       <property name="sessionFactory" ref="sessionFactory" />  
  55.    </bean>  
  56.      
  57.    <!-- 配置事务异常封装 -->  
  58.    <bean id="persistenceExceptionTranslationPostProcessor"   
  59.        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />  
  60.   
  61. </beans>  

第一节中xml配置事务中需要通过配置tx:advice和aop:config来增加事务的功能。此处采用全注释方法,这两个配置节就不需要了。

 

相应的需要在视图解析配置中启用注释,如下lei-dispatcher-servlet.xml


[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  5.     xmlns:p="http://www.springframework.org/schema/p"  
  6.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  7.     xmlns:tx="http://www.springframework.org/schema/tx"  
  8.     xsi:schemaLocation="  
  9.         http://www.springframework.org/schema/beans       
  10.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  11.         http://www.springframework.org/schema/context  
  12.         http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  13.         http://www.springframework.org/schema/mvc  
  14.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  15.         http://www.springframework.org/schema/tx  
  16.         http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
  17.         ">  
  18.           
  19.     <!-- 启动自动扫描 该包下所有的Bean(@Controller) -->  
  20.     <context:component-scan base-package="com.lei.demo" />  
  21.       
  22.     <!-- 基于注释的事务,当注释中发现@Transactional时,使用id为“transactionManager”的事务管理器  -->  
  23.     <!-- 如果没有设置transaction-manager的值,则spring以缺省默认的事务管理器来处理事务,默认事务管理器为第一个加载的事务管理器 -->  
  24.     <tx:annotation-driven transaction-manager="transactionManager"/>  
  25.       
  26.     <!-- 定义视图解析器 -->  
  27.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  28.         <property name="prefix">  
  29.             <value>/WEB-INF/user/</value>  
  30.         </property>  
  31.         <property name="suffix">  
  32.             <value>.jsp</value>  
  33.         </property>  
  34.     </bean>  
  35.       
  36. </beans>  

UserDAO如下


[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.lei.demo.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.annotation.Resource;  
  6.   
  7. import org.hibernate.Query;  
  8. import org.hibernate.Session;  
  9. import org.hibernate.SessionFactory;  
  10. import org.springframework.stereotype.Repository;  
  11.   
  12. import com.lei.demo.entity.Users;  
  13.   
  14. @Repository  
  15. public class UsersDAO {  
  16.     @Resource(name="sessionFactory")  
  17.     private SessionFactory sessionFactory;  
  18.   
  19.     public void setSessionFactory(SessionFactory sessionFactory) {  
  20.         this.sessionFactory = sessionFactory;  
  21.     }  
  22.   
  23.     public SessionFactory getSessionFactory() {  
  24.         return sessionFactory;  
  25.     }  
  26.   
  27.     public List<Users> getAllUser(){  
  28.         String hsql="from users";  
  29.         Session session = sessionFactory.getCurrentSession();  
  30.         Query query = session.createQuery(hsql);  
  31.           
  32.         return query.list();  
  33.     }  
  34. }  

UserService.java如下


[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.lei.demo.service;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Service;  
  6. import org.springframework.transaction.annotation.Isolation;  
  7. import org.springframework.transaction.annotation.Propagation;  
  8. import org.springframework.transaction.annotation.Transactional;  
  9.   
  10. import com.lei.demo.dao.*;  
  11.   
  12. @Service("userService")  
  13. public class UserService {  
  14.     @Resource  
  15.     private UsersDAO userDao;  
  16.       
  17.     @Transactional  
  18.     public int userCount(){  
  19.         return userDao.getAllUser().size();  
  20.     }  
  21.   
  22.     public UsersDAO getUserDao() {  
  23.         return userDao;  
  24.     }  
  25.   
  26.     public void setUserDao(UsersDAO userDao) {  
  27.         this.userDao = userDao;  
  28.     }  
  29.   
  30. }  

这里,方法名userCount上加入@Transactional,说明这个方法要启用事务。如果类名UserService上加入@Transactional,则表明这个类中的所有方法都会启用事务。

如果配有多个transactionManager,例如配置有transactionManager1,和transactionManager2,则可以通过@Transactional(“transactionManager1”),的方式指定使用哪个数据源的事务。

 

源代码下载:

http://www.oschina.net/code/snippet_1764868_35775

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值