Dao层进行事务的添加,实现异常回滚

dao层代码,实现回滚

事务提交前扔出来了一个异常,运行结果,数据库中没有插入值

package com.uu.translation.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Repository
public class UserDao {
     
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public void insert() {
     
        DataSourceTransactionManager txManager=new DataSourceTransactionManager();
//给事务管理器添加数据源
        txManager.setDataSource(jdbcTemplate.getDataSource());
//定义事务
        DefaultTransactionDefinition transaction=new DefaultTransactionDefinition();
//设置事务隔离级别
        transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
//设置事务传播级别
        transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status=txManager.getTransaction(transaction);
//设置事务传播和隔离级别
        String sql = "INSERT INTO tem(id,str) VALUES(122,'s')";
        jdbcTemplate.execute(sql);
        if(10 == 10)
        throw new RuntimeException();
        //事务提交
        txManager.commit(status);
    }
}

dao层代码,不回滚

此时,即使抛出了异常 ,也进行了数据库的修改

package com.uu.translation.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserDao {
     
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public void insert() {
     
        String sql = "INSERT INTO tem(id,str) VALUES(122,'s')";
        jdbcTemplate.execute(sql);
        if(10 == 10)
        throw new RuntimeException();
    }
}

你可能感兴趣的:(框架基础知识,spring)