码迷,mamicode.com
首页 > 编程语言 > 详细

spring事务处理详解

时间:2015-08-25 19:38:08      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:spring   事务   异常   

1:Java包含两种异常:checked异常和unchecked异常。

checked和unchecked异常之间的区别是:
Checked异常必须被显式地捕获try-catch-finally,而unchecked异常则可以不必捕获或抛出。
Checked异常继承java.lang.Exception类。Unchecked异常继承自java.lang.RuntimeException类。

2:Mysql 存储引擎中InnoDB与Myisam的主要区别

事务处理方面:innodb 支持事务功能,myisam 不支持。
Myisam 的执行速度更快,性能更好。

engine = innodb 和 engine = myisam
可使用下述语句之一检查表的表类型:
SHOW TABLE STATUS LIKE ‘tbl_name’;
SHOW CREATE TABLE tbl_name;

使用下述语句,可检查mysqld服务器支持的存储引擎:
SHOW ENGINES;

3:spring事务处理

throw new RuntimeException(“xxxxxxxxxxxx”); 默认事务回滚
throw new Exception(“xxxxxxxxxxxx”); 默认事务不回滚
Spring的AOP即声明式事务管理默认是针对unchecked exception回滚。也就是默认对RuntimeException()异常或是其子类进行事务回滚;
checked异常,throw new Exception默认不会回滚

若想让checked异常或者自定义异常回滚
(1)配置文件方式

<tx:advice id="txAdvice">
    <tx:attributes>
       <tx:method name="update*" no-rollback-for="IOException"/>
       <tx:method name="*"/>
    </tx:attributes>
 </tx:advice>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
   <tx:attributes>
     <tx:method name="*" rollback-for="com.cn.untils.exception.MyException"/>
   </tx:attributes>
 </tx:advice>

(2)注解方式

@Transactional(rollbackFor = Exception.class)
 @Transactional(rollbackFor = MyException.class)

不起作用:

@Transactional
public void addAdmin(Admin admin) throws Exception {
    try {
        this.adminDao.add(admin);
        admin.setUsername("123456789012345");
        this.adminDao.update(admin);
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("测试!");
    }

}

起作用

@Transactional(rollbackFor = Exception.class)
public void addAdmin(Admin admin) throws Exception {
    try {
        this.adminDao.add(admin);
        admin.setUsername("123456789012345");
        this.adminDao.update(admin);
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("测试!");
    }

}

起作用

@Transactional
public void addAdmin(Admin admin) {
    try {
        this.adminDao.add(admin);
        admin.setUsername("123456789012345");
        this.adminDao.update(admin);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("测试!");
    }

}

完整写法:

@Transactional(rollbackFor = RuntimeException.class)
public void addAdmin(Admin admin) {
    try {
        this.adminDao.add(admin);
        admin.setUsername("123456789012345");
        this.adminDao.update(admin);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("测试!");
    }

版权声明:本文为博主原创文章,未经博主允许不得转载。

spring事务处理详解

标签:spring   事务   异常   

原文地址:http://blog.csdn.net/u013628152/article/details/47980811

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!