Spring中的声明式事务管理

tech2025-11-10  5

1)配置信息中引入事务的命名空间

 xmlns:tx="http://www.springframework.org/schema/tx"  http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx.xsd

 2)启用事务:用注解驱动的方式来管理事务

            <tx:annotation-driven/>

3)在 spring.xml 中配置事务管理器 : id=" transcationManager " 

     <!-- 5)配置事务管理器          id="transactionManager" id名必须是transactionManager,不能更改      -->     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">         <property name="dataSource" ref="dataSource"/>     </bean>

  4) 在要使用事务的方法或类上,添加注解 @Transcational,spring会自动提交,回滚事务

 /**      事务注解(@Transactional):               加在方法上,表示此方法受事务管理(自动提交,回滚事务)               加在类上,那么这个类中的所有方法都受事务管理        最后要注意的是,在业务方法中不要自己try-catch捕获异常,否则spring无法自动回滚事务  */     @Transactional     public void business1(){         productMapper.delete(100000005);         productMapper.delete(100000006);         int i = 1/0;         productMapper.delete(100000007);       }

 

 

 

 

 

 

 

 

 

 

 

最新回复(0)