spring boot开启事务管理,使用事务的回滚机制,使两条插入语句一致

spring boot 事务管理,使用事务的回滚机制

1:配置事务管理

     在springboot 启动类中添加

@EnableTransactionManagement    //开启事务管理
@EnableAsync(proxyTargetClass=true)    //配置代理为cglib代理,默认使用 的是jdk动态代理

2:配置管理器

     

package com.li;

import javax.sql.DataSource;

@EnableAutoConfiguration
@SpringBootApplication
@MapperScan("com.li.dao")
@EnableTransactionManagement
@EnableAsync(proxyTargetClass=true)
public class SpringBootLabApplication {
    public static void main(String[] args){
        SpringApplication.run(SpringBootLabApplication.class, args);
    }

    // 创建事务管理器1
    @Bean(name = "txManager1")  //给事务管理器命名
    public PlatformTransactionManager txManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}

3:在@Service类的方法上添加 @Transactional(value="事务名")

    @Transactional(value="txManager1")
    @Override
    public boolean insert(InsertParameter parameter) throws Exception {   //如果想让两条插入语句共同执行,异常一定要抛出
        int i1=manageMapper.insertNewsList(parameter);;
        int i2=manageMapper.insertNews(parameter);

        if (i1!=i2 || i1!=1) {
            return false;
        }
        return true;
    }

   4:ok

     

猜你喜欢

转载自www.cnblogs.com/liyafei/p/9065797.html