spring(基础七) spring事务回滚详解

来源:互联网 发布:电影解析采集源码 编辑:程序博客网 时间:2024/06/07 19:44

(一) 用编程的方法来实现,我觉得这种方法比较灵活,控制起来比较方便,但是需要写一些额外的代码

1.1 定义bean:

<!--定义Bean-->    <bean id="Test" class="com.test.Test">        <property name="template" ref="jdbcTemplate" />        <property name="transaction" ref="transactionTemplate" />    </bean> 

1.2 事务配置:
<!--事务模板 -->    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">             <property name="transactionManager">                      <ref local="transactionManager"/>             </property>    </bean> 
<!-- jdbc事务管理器 -->    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">             <property name="dataSource">                      <ref local="dataSource"/>     </property>

1.3 测试类
public class Test {    private JdbcTemplate template;    private TransactionTemplate transaction;    private static final String TEST_SQL="insert into user(name,date) values(?,?)";    public void setTemplate(JdbcTemplate template) {        this.template = template;    }    public void setTransaction(TransactionTemplate transaction) {        this.transaction = transaction;    }    public  void testSQL() throws Exception{        for(int i=0;i<10;i++){            if(i==8)throw new Exception("====error when updaa=======");//到第八条数据时我抛异常            template.update(TEST_SQL,new Object[]{"xugang"+i,"123"});        }           }    public static void main(String[] args) throws Exception{        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");        final Test t=(Test)ctx.getBean("Test");        boolean f=t.transaction.execute(new TransactionCallback<Boolean>() {            @Override            public Boolean doInTransaction(TransactionStatus status) {                    try {                            t.testSQL();//测试SQL                        return Boolean.TRUE;//插入成功                    } catch (Exception e) {                        // TODO Auto-generated catch block                        status.setRollbackOnly();//回滚事物                        e.printStackTrace();                        return Boolean.FALSE;                    }            }        });}



(二)用声明的方法来实现事物的管理,在配置文件中加入下面

 <tx:advice id="txAdvice" transaction-manager="transactionManager">        <tx:attributes>            <tx:method name="get*" read-only="true" /><!--以get开头的方法中的Connection是readonly的 -->            <tx:method name="update*" rollback-for="Throwable"/><!-- 在update开头的方法中遇到异常(Throwable)就回滚-->            <tx:method name="*" />        </tx:attributes>    </tx:advice>    <aop:config>        <aop:pointcut expression="execution(* com.test.Test2.*(..))"<!-- 匹配com.test.Test2这个类下面的所有方法-->            id="service" />        <aop:advisor advice-ref="txAdvice" pointcut-ref="service" />    </aop:config>/** * 测试事物回滚 * @author 许刚 */public class Test2 {    private JdbcTemplate template;    private TransactionTemplate transaction;    private static final String TEST_SQL="insert into user(name,date) values(?,?)";    public void setTemplate(JdbcTemplate template) {        this.template = template;    }    public void setTransaction(TransactionTemplate transaction) {        this.transaction = transaction;    }    public  void testSQL() throws Exception{        for(int i=0;i<10;i++){            if(i==8)throw new Exception("====error when updaa=======");            template.update(TEST_SQL,new Object[]{"xugang"+i,"123"});        }            }        public void getData(){        template.update(TEST_SQL,new Object[]{"xugang","123"});    }    public void updateData() throws Exception{        testSQL();    }        public static void main(String[] args) throws Exception{        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");        final Test2 t=(Test2)ctx.getBean("Test2");        //t.getData();//get开头的方法是readonly的就会抛下面的异常        //  java.sql.SQLException: Connection is read-only. Queries leading to data modification are not allowed        t.updateData();//执行玩了以后,数据库里面一条数据都没有的,在第8条的时候回滚了    }}

0 0
原创粉丝点击