spring控制事务的回滚

要解决上面的问题,首先我们要分清楚什么是checked检查异常和unchecked非检查异常。

一、checked异常就是抛出Excetion异常以及其子类异常,spring默认对它是不回滚事务,要特别注意。

eg:

public void delete(Integer Personageid) throws Exception{  
        jdbcTemplate.update("delete from Personage where id=?", new Object[]{Personageid},  
        new int[]{java.sql.Types.INTEGER});  
        throw new Exception("运行期例外");  
    }  

使用try..catch操作也是不回滚事务的。没有抛异常,所以事务不回滚

eg:

public void delete(Integer Personageid) {  
        try{
            jdbcTemplate.update("delete from Personage where id=?", new Object[]{Personageid},  
            new int[]{java.sql.Types.INTEGER});  
        }catch(Exception e){
             e.printStackTrace()
        }
        
       
    }  

要解决上面的问题:(1)可以在方法上使用@Transactional(rollbackFor=Exception.class),并且throw Exception  这样就可以回滚

@Transactional(rollbackFor=Exception.class)  
    //rollbackFor这属性指定了,既使你出现了checked这种例外,那么它也会对事务进行回滚  
    public void delete(Integer personid) throws Exception{  
        jdbcTemplate.update("delete from person where id=?", new Object[]{personid},  
        new int[]{java.sql.Types.INTEGER});  
        throw new Exception("运行期例外");  
    }  

(2)使用try...catch..throws excetion。也可以回滚事务

//前提是类上使用了注解@Transational
@Transational(rollback=Excepiton.class)
public void delete(Integer Personageid) throws Exception {  
        try{
            jdbcTemplate.update("delete from Personage where id=?", new Object[]{Personageid},  
            new int[]{java.sql.Types.INTEGER});  
        }catch(Exception e){
             e.printStackTrace();
              throw new Exception("异常");
        }
 }  

二、unchecked异常(RuntimeException),spring默认是事务回滚的

eg:

//发生了unchecked异常,事务回滚, @Transactional  
    public void del(Integer Personageid){  
        jdbcTemplate.update("del from Personage where id=?", new Object[]{Personageid},  
        new int[]{java.sql.Types.INTEGER});  
        throw new RuntimeException("运行期例外");  
    }  

猜你喜欢

转载自blog.csdn.net/jaryle/article/details/88593961