Mybatis-plus多数据源情况下saveBatch报错Resource must not be null

问题如上,对测试环境做了mysql读写分离的改造,增加了mybatis-plus多数据配置,其他情况一切顺利,但在执行saveBatch方法的时候会提示Resource must not be null。

下图中的sqlSessionFactory()方法中最开始用的是SqlSessionFactoryBean,这个是spring集成mybatis中提供的,然后再测试环境中执行saveBatch就一直报Resource must not be null错误,后来经过debug分析,发现需要使用mybatis-plus自带的MybatisSqlSessionFactoryBean操作可以解决。简单分析一下就是,mybatis-plus自己封装的MybatisSqlSessionFactoryBean多了一个GlobalConfig属性,在执行saveBatch方法的时候会去通过操作GlobalConfig,生成sqlSessionFactory,而mybatis中的SqlSessionFactoryBean是不带这个属性的,所以如果通过SqlSessionFactoryBean去生成SqlSessionFactory它的globalConfig就为空,在后续的操作上直接抛出了异常。

总结:Mybatis-plus集成多数据源的情况下,建议使用MybatisSqlSessionFactoryBean去生成SqlSessionFactory,可以减少一些不必要的麻烦。

上代码:

mybatis-plus的配置类

package com.ahc.ahjr.common.config;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Objects;

/**
 * mybatis-plus配置类
 * @
 */
@Configuration
@EnableTransactionManagement
@MapperScan("com.module.*.mapper")
public class MybatisPlusConfig {

    @Resource(name="targetDataSource")
    private DataSource dataSource;

    @Autowired
    private Environment env;


    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
        paginationInterceptor.setMaxLimit(10000L);
        mybatisPlusInterceptor.addInnerInterceptor(paginationInterceptor);
        return mybatisPlusInterceptor;
    }


    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        //这个是正确的
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/ahc/modules/**/xml/*.xml"));
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setLogImpl(StdOutImpl.class);
        configuration.setCacheEnabled(false);
        sqlSessionFactoryBean.setConfiguration(configuration);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager()  {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory)  {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


}

saveBatch的部分源码:

  public static boolean executeBatch(Class<?> entityClass, Log log, Consumer<SqlSession> consumer) {
        try {
			//sqlSessionFactory(entityClass)方法只需深入底层会去找GlobalConfigUtils生成sqlSessionFactory,这一步如果mybatisplus配置类中用的是SqlSessionFactoryBean,此时返回的sqlSessionFactory为null
            SqlSessionFactory sqlSessionFactory = sqlSessionFactory(entityClass);
            SqlSessionHolder sqlSessionHolder = (SqlSessionHolder)TransactionSynchronizationManager.getResource(sqlSessionFactory);
            boolean transaction = TransactionSynchronizationManager.isSynchronizationActive();
            SqlSession sqlSession;
            if (sqlSessionHolder != null) {
                sqlSession = sqlSessionHolder.getSqlSession();
                sqlSession.commit(!transaction);
            }

            sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
            if (!transaction) {
                log.warn("SqlSession [" + sqlSession + "] Transaction not enabled");
            }

            boolean var7;
            try {
                consumer.accept(sqlSession);
                sqlSession.commit(!transaction);
                var7 = true;
            } catch (Throwable var15) {
                sqlSession.rollback();
                Throwable unwrapped = ExceptionUtil.unwrapThrowable(var15);
                if (unwrapped instanceof PersistenceException) {
                    MyBatisExceptionTranslator myBatisExceptionTranslator = new MyBatisExceptionTranslator(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true);
                    Throwable throwable = myBatisExceptionTranslator.translateExceptionIfPossible((PersistenceException)unwrapped);
                    if (throwable != null) {
                        throw throwable;
                    }
                }

                throw ExceptionUtils.mpe(unwrapped);
            } finally {
                sqlSession.close();
            }

            return var7;
        } catch (Throwable var17) {
            throw var17;
        }
    }

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值