深入理解事务--Spring注解式事务配置注意事项

1. 在需要事务管理的地方加@Transactional 注解。

@Transactional 注解可以被应用于接口定义和接口方法、类定义和类的 public 方法上。

2. @Transactional 注解只能应用到 public 可见度的方法上。

 如果你在 protected、private 或者 package-visible 的方法上使用 @Transactional 注解,它也不会报错, 但是这个被注解的方法将不会展示已配置的事务设置。

3. 注意仅仅 @Transactional 注解的出现不足于开启事务行为,它仅仅 是一种元数据。必须在配置文件中使用配置元素,才真正开启了事务行为。

 详见最下面的配置实例

4. 通过 元素的 "proxy-target-class" 属性值来控制是基于接口的还是基于类的代理被创建。

如果 "proxy-target-class" 属值被设置为 "true",那么基于类的代理将起作用(这时需要CGLIB库cglib.jar在CLASSPATH中)。

如果 "proxy-target-class" 属值被设置为 "false" 或者这个属性被省略,那么标准的JDK基于接口的代理将起作用。


<!--标准的JDK基于接口的代理将起作用-->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false"/>
<!--基于类的代理将起作用 ,同时 cglib.jar必须在CLASSPATH中-->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>


非JTA事务(即非分布式事务), 事务配置的时候 ,事务管理器(transactionManager)需要指定dataSource属性(非分布式事务,事务是在数据库创建的链接上开启。)

JTA事务(分布式事务), 事务配置的时候 ,事务管理器(transactionManager)不能指定dataSource属性(分布式事务,是有全局事务来管理数据库链接的)


注解@Transactional cglib与java动态代理最大区别是代理目标对象不用实现接口,那么注解要是写到接口方法上,要是使用cglib代理,这是注解事物就失效了,为了保持兼容注解最好都写到实现类方法上。

5. Spring团队建议在具体的类(或类的方法)上使用 @Transactional 注解,而不要使用在类所要实现的任何接口上。

在接口上使用 @Transactional 注解,只能当你设置了基于接口的代理时它才生效。因为注解是 不能继承 的,这就意味着如果正在使用基于类的代理时,那么事务的设置将不能被基于类的代理所识别,而且对象也将不会被事务代理所包装。

6. @Transactional 的事务开启 ,或者是基于接口的 或者是基于类的代理被创建。

所以在同一个类中一个方法调用另一个方法有事务的方法,事务是不会起作用的。

[java]  view plain  copy
  1. public interface PersonService {  
  2. //删除指定id的person  
  3. public void delete(Integer personid) ;  
  4. //删除指定id的person,flag  
  5. public void delete(Integer personid,boolean flag) ;  
  6. }  
  7. public class PersonServiceBean implements PersonService {  
  8. private JdbcTemplate jdbcTemplate;  
  9.   
  10.   
  11. public void delete(Integer personid){  
  12. try{  
  13. this.delete(personid,true)  
  14. System.out.println("delete success");  
  15. }catch(Exception e){  
  16. System.out.println("delete failed");  
  17. }  
  18. }  
  19. @Transactional  
  20. //此时,事务根本就没有开启, 即数据库会默认提交该操作,即记录别删除掉 public void delete(Integer personid,boolean flag){  
  21. if(flag == ture){  
  22. jdbcTemplate.update("delete from person where id=?"new Object[]{personid},  
  23. new int[]{java.sql.Types.INTEGER});  
  24. throw new RuntimeException("运行期例外");  
  25. }  
  26. }  
  27. }  
  28. public class PersonServiceBeanTest{  
  29. PersonService ps = new PersonServiceBean ();  
  30. ps.delete(5);  
  31. }  


7. Spring使用声明式事务处理,默认情况下,如果被注解的数据库操作方法中发生了unchecked异常,所有的数据库操作将rollback;如果发生的异常是checked异常,默认情况下数据库操作还是会提交的。

[java]  view plain  copy
  1. public interface PersonService {  
  2. //删除指定id的person  
  3. public void delete(Integer personid) ;  
  4. //获取person  
  5. public Person getPerson(Integer personid);  
  6. }  
  7. //PersonServiceBean 实现了PersonService 接口,则基于接口的还是基于类的代理 都可以实现事务  
  8. @Transactional public class PersonServiceBean implements PersonService {  
  9. private JdbcTemplate jdbcTemplate;  
  10.   
  11.   
  12. //发生了unchecked异常,事务回滚, @Transactional  
  13. public void delete(Integer personid){  
  14. jdbcTemplate.update("delete from person where id=?"new Object[]{personid},  
  15. new int[]{java.sql.Types.INTEGER});  
  16. throw new RuntimeException("运行期例外");  
  17. }  
  18. }  
  19. ---------------------------------------------------------------------------------------------------------------------------------------------------  
  20. public interface PersonService {  
  21. //删除指定id的person  
  22. public void delete(Integer personid) throws Exception;  
  23. //获取person  
  24. public Person getPerson(Integer personid);  
  25. }  
  26. @Transactional  
  27. public class PersonServiceBean implements PersonService {  
  28. //发生了checked异常,事务不回滚,即数据库记录仍能被删除,  
  29. //checked的例外,需要我们在外部用try/catch语法对调用该方法的地方进行包含 @Transactional  
  30. public void delete(Integer personid) throws Exception{  
  31. jdbcTemplate.update("delete from person where id=?"new Object[]{personid},  
  32. new int[]{java.sql.Types.INTEGER});  
  33. throw new Exception("运行期例外");  
  34. }  
  35. }  
  36. ---------------------------------------------------------------------------------------------------------------------------------------------------  
  37. 但是,对于checked这种例外,默认情况下它是不会进行事务回滚的,但是如果我们需要它进行事务回滚,这时候可以在delete方法上通过@Transaction这个注解来修改它的行为。  
  38. @Transactional  
  39. public class PersonServiceBean implements PersonService {  
  40.   
  41.   
  42. @Transactional(rollbackFor=Exception.class)  
  43. //rollbackFor这属性指定了,既使你出现了checked这种例外,那么它也会对事务进行回滚  
  44. public void delete(Integer personid) throws Exception{  
  45. jdbcTemplate.update("delete from person where id=?"new Object[]{personid},  
  46. new int[]{java.sql.Types.INTEGER});  
  47. throw new Exception("运行期例外");  
  48. }  
  49. }  



在PersonServiceBean这个业务bean里面,有 一些事务是不需要事务管理的,好比说获取数据的getPersons方法,getPerson方法。因为@Transactional 放在了类的上面。

此时,可以采用propagation这个事务属性@Transactional(propagation=Propagation.NOT_SUPPORTED)

propagation这个属性指定了事务传播行为,我们可以指定它不支持事务,当我们这么写了之后,Spring容器在getPersons方法执行前就不会开启事务.

[java]  view plain  copy
  1. @Transactional  
  2. public class PersonServiceBean implements PersonService {  
  3.   
  4.   
  5. @Transactional(propagation=Propagation.NOT_SUPPORTED)  
  6. //则此方法 就不会开启事务了  
  7. public Person getPerson(Integer personid)  
  8. {  
  9. }  
  10. }  


#######################################################

混合事务配置实例:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns:aop="http://www.springframework.org/schema/aop"  
  3.     xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="  
  6.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  7.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd  
  8.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd  
  9.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  ">  
  10.   
  11.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" >  
  12.         <property name="driverClass" value="${db.driver}"></property>  
  13.         <property name="jdbcUrl" value="${db.url}"></property>  
  14.         <property name="user" value="${db.username}"></property>  
  15.         <property name="password" value="${db.password}"></property>  
  16.         <property name="acquireIncrement" value="2"></property>  
  17.         <property name="preferredTestQuery" value="select 1 from dual"></property>  
  18.         <!-- <property name="idleConnectionTestPeriod" value="60"></property> -->  
  19.         <property name="initialPoolSize" value="${db.minPoolSize}"></property>  
  20.         <property name="minPoolSize" value="${db.minPoolSize}"></property>  
  21.         <property name="maxPoolSize" value="${db.maxPoolSize}"></property>  
  22.         <property name="maxIdleTime" value="${db.maxIdleTime}"></property>  
  23.     </bean>  
  24.   
  25.     <!-- Transaction manager :  
  26.     非JTA事务(即非分布式事务), 事务配置的时候 ,事务管理器(transactionManager)需要指定dataSource属性(非分布式事务,事务是在数据库创建的链接上开启。)  
  27.     JTA事务(分布式事务), 事务配置的时候 ,事务管理器(transactionManager)不能指定dataSource属性(分布式事务,是有全局事务来管理数据库链接的)  
  28.     -->  
  29.     <bean id="transactionManager"  
  30.         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  31.         <property name="dataSource" ref="dataSource" />  
  32.     </bean>  
  33.   
  34.     <!-- 使用注解annotation定义事务:   
  35.     如果 "proxy-target-class" 属值被设置为 "true",那么基于类的代理将起作用(这时需要CGLIB库cglib.jar在CLASSPATH中)。  
  36.     如果 "proxy-target-class" 属值被设置为 "false" 或者这个属性被省略,那么标准的JDK基于接口的代理将起作用。  
  37.   
  38.     -->  
  39.         <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />  
  40.       
  41.   
  42.     <!-- 使用AOP transaction定义事务 -->  
  43.     <tx:advice id="defaultTxAdvice" transaction-manager="transactionManager">  
  44.        <tx:attributes>  
  45.         <tx:method name="get*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />  
  46.             <tx:method name="query*" read-only="true" />  
  47.             <tx:method name="search*" read-only="true" />  
  48.             <tx:method name="select*" read-only="true" />  
  49.             <tx:method name="find*" read-only="true" />  
  50.             <tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />  
  51.             <tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />  
  52.             <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />  
  53.             <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />  
  54.             <tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />  
  55.             <tx:method name="do*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />  
  56.         <tx:method name="execute*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />  
  57.         <tx:method name="*" read-only="true" propagation="REQUIRED" isolation="DEFAULT" />  
  58.      </tx:attributes>  
  59.     </tx:advice>  
  60.   
  61.     <tx:advice id="logTxAdvice" transaction-manager="transactionManager">    
  62.          <tx:attributes>    
  63.             <tx:method name="get*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />  
  64.             <tx:method name="query*" read-only="true" />  
  65.             <tx:method name="search*" read-only="true" />  
  66.             <tx:method name="select*" read-only="true" />  
  67.             <tx:method name="find*" read-only="true" />  
  68.             <tx:method name="*" propagation="REQUIRES_NEW"    
  69.                 rollback-for="java.lang.Exception" />    
  70.          </tx:attributes>    
  71.         </tx:advice>   
  72.     <!-- "order"参数,这个参数是用来控制aop通知的优先级,值越小,优先级越高 ,混合事务配置时要制定该参数。  
  73.         execution:使用“execution(方法表达式)”匹配方法执行  
  74.         within:使用“within(类型表达式)”匹配指定类型内的方法执行  
  75.      -->  
  76.     <aop:config>  
  77.         <aop:pointcut id="defaultOperation"    
  78.             expression="execution(* *..*ServiceImpl.*(..))" />    
  79.             <aop:pointcut id="logServiceOperation"    
  80.             expression="@within(com.homent.service.LogService+" />    
  81.                 
  82.             <aop:advisor advice-ref="defaultTxAdvice" order="3" pointcut-ref="defaultOperation" />    
  83.             <aop:advisor advice-ref="logTxAdvice" order="2" pointcut-ref="logServiceOperation" />    
  84.     </aop:config>  
  85.   
  86.   
  87. </beans>  



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring事务是一种在开发应用程序时常用的技术,用于管理数据库操作的一致性和隔离性。声明事务是一种可以通过注解配置文件来定义事务行为的方,而不需要在代码中显地编写事务管理逻辑。 声明事务使用了AOP(面向切面编程)的概念,通过在业务逻辑上定义切点,然后在切点上应用事务通知来实现事务的管理。在Spring中,我们可以使用@Transactional注解来标记事务的边界,告诉Spring该方法应该在事务中运行。同时,我们也可以使用XML配置文件来声明事务的属性,例如隔离级别、传播行为和回滚规则等。 使用声明事务的好处是可以将事务管理逻辑从业务逻辑中分离出来,使代码更加简洁和可维护。此外,声明事务还提供了更高的灵活性,可以根据不同的业务需求来配置不同的事务特性。 然而,使用声明事务也存在一些注意事项。首先,需要确保在Spring配置文件中启用了事务管理器,并正确配置了数据源。其次,需要注意事务的传播行为,要确保方法调用链中所有涉及事务的方法在同一个事务中执行。最后,还需要注意异常的处理方,确定哪些异常会触发事务的回滚。 总之,Spring的声明事务提供了一种便捷且灵活的方来管理数据库事务,使代码更加简洁和可维护。但在使用时需要注意相关的配置事务的传播行为,以确保事务的正确执行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值