springboot项目双数据源一个方法里面调用多个方法时,事务失效解决方法

先说问题:我有一个A方法,里面调用了B,C等方法,B,C方法里都有插入操作,在发生错误时,没有回滚,事务失效了。
只针对双数据源(从mysql查询插入到oracle中),单数据源没有这么麻烦,后续会更新
解决办法:1 先看有没有加注解@Transactional,如果没加,请加上。
2.把A和B,C分开,B,C单独写一个类。
3.还需要在写一个save方法,调用B,C,A在调用save方法,注意:在save方法上加注解@Transactional
4.新建一个config文件夹,在config文件夹下新建DataSourceConfig1和DataSourceConfig2
在这里插入图片描述
DataSourceConfig1的内容是:
@Configuration
@MapperScan(basePackages = “com.inspur.wfmigration.org.datamigration.dao.db1”, sqlSessionFactoryRef = “db1SqlSessionFactory”)
public class DataSourceConfig1 {

@Primary // 表示这个数据源是默认数据源, 这个注解必须要加,因为不加的话spring将分不清楚那个为主数据源(默认数据源)
@Bean("db1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.db1") //读取application.yml中的配置参数映射成为一个对象
public DataSource getDb1DataSource(){
    return DataSourceBuilder.create().build();
}

@Primary
@Bean("db1SqlSessionFactory")
public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    // mapper的xml形式文件位置必须要配置,不然将报错:no statement (这种错误也可能是mapper的xml中,namespace与项目的路径不一致导致)
    bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:queryMapper/db1/*.xml"));
    return bean.getObject();
}

@Primary
@Bean("db1SqlSessionTemplate")
public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
    return new SqlSessionTemplate(sqlSessionFactory);
}
**DataSourceConfig2的内容是:**
@Configuration

@MapperScan(basePackages = “com.inspur.wfmigration.org.datamigration.dao.db2”, sqlSessionFactoryRef = “db2SqlSessionFactory”)
public class DataSourceConfig2 {

@Bean("db2DataSource")
@ConfigurationProperties(prefix = "spring.datasource.db2")
public DataSource getDb1DataSource(){
    return DataSourceBuilder.create().build();
}

@Bean("db2SqlSessionFactory")
public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:queryMapper/db2/*.xml"));
    return bean.getObject();
}

@Bean("db2SqlSessionTemplate")
public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
    return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean("txManager2")
public DataSourceTransactionManager txManager2(@Qualifier("db2DataSource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
}

就可以了,亲测有效


版权声明:本文为weixin_41269213原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。