spring进阶(二)事务

来源:互联网 发布:淘宝客服外包怎么运营 编辑:程序博客网 时间:2024/06/03 21:04

1. spring事务的回滚

    spring的事务,一般配置在service层

    spring事务中,不能使用try{...}catch{.....},否则不会发生回滚

     service层抛出的异常,必须是RunTimeException或者其它子类的异常,否则不会发生回滚

示例:

public void save() throws Exception{User user = new User() ;user.setId("111111") ;user.setName("xiaoming") ;user.setPassword("password") ;userMapper.insert(user) ; save2();}public void save2() throws Exception{User user1 = new User() ;user1.setId("222222") ;user1.setName("xiaoxi") ;user1.setPassword("2222222222") ;if(1!=3){throw new RuntimeException();}userMapper.insert(user1) ;}


2. spring事务的配置文件

<?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: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-4.0.xsd           http://www.springframework.org/schema/tx           http://www.springframework.org/schema/tx/spring-tx-4.0.xsd           http://www.springframework.org/schema/aop                 http://www.springframework.org/schema/aop/spring-aop-4.0.xsd               "><!--  配置事务管理器,配置切面,配置切面的行为 --><!-- 事务管理器 --><bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- 数据源 --><property name="dataSource" ref="dataSource" /></bean><!-- 通知                切面的行为,下面配置切面 --><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><!-- 传播行为 --><tx:method name="save*" propagation="REQUIRED" /><!-- 在事务中执行 --><tx:method name="insert*" propagation="REQUIRED" /><tx:method name="add*" propagation="REQUIRED" /><tx:method name="create*" propagation="REQUIRED" /><tx:method name="delete*" propagation="REQUIRED" /><tx:method name="update*" propagation="REQUIRED" /><tx:method name="find*" propagation="SUPPORTS" read-only="true" /><!-- 有事务,在事务中执行,没有的话,不会开启新的事务 --><tx:method name="select*" propagation="SUPPORTS" read-only="true" /><tx:method name="get*" propagation="SUPPORTS" read-only="true" /></tx:attributes></tx:advice><!-- 配置切面 --><aop:config><aop:advisor advice-ref="txAdvice"pointcut="execution(* com.whir.springmvc.service.*.*(..))" /></aop:config></beans>




0 0
原创粉丝点击