mybatis-plus 3.5.7版本mapper在insertOrUpdate方法时sqlSessionFactory为null的问题

default List<BatchResult> insertOrUpdate(Collection<T> entityList, BiPredicate<BatchSqlSession, T> insertPredicate, int batchSize) {
    MybatisMapperProxy<?> mybatisMapperProxy = MybatisUtils.getMybatisMapperProxy(this);
    MybatisBatch.Method<T> method = new MybatisBatch.Method<>(mybatisMapperProxy.getMapperInterface());
    SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory(mybatisMapperProxy);
    return MybatisBatchUtils.saveOrUpdate(sqlSessionFactory, entityList, method.insert(), insertPredicate, method.updateById(), batchSize);
}

insertOrUpdate方法调用MybatisUtils.getSqlSessionFactory获取SqlSessionFactory

if (sqlSession instanceof DefaultSqlSession) {
    // TODO 原生mybatis下只能这样了.
    return GlobalConfigUtils.getGlobalConfig(mybatisMapperProxy.getSqlSession().getConfiguration()).getSqlSessionFactory();
}

会通过GlobalConfig去拿SqlSessionFactory

public static GlobalConfig getGlobalConfig(Configuration configuration) {
    Assert.notNull(configuration, "Error: You need Initialize MybatisConfiguration !");
    final String key = Integer.toHexString(configuration.hashCode());
    return CollectionUtils.computeIfAbsent(GLOBAL_CONFIG, key, k -> defaults());
}

里面有一个Map GLOBAL_CONFIG,这个map通过setGlobalConfig进行添加

public static void setGlobalConfig(Configuration configuration, GlobalConfig globalConfig) {
    Assert.isTrue(configuration != null && globalConfig != null, "Error: Could not setGlobalConfig");
    // 设置全局设置
    GLOBAL_CONFIG.putIfAbsent(Integer.toHexString(configuration.hashCode()), globalConfig);
}

这个setGlobalConfig方法是在MybatisSqlSessionFactoryBean中的buildSqlSessionFactory调用的,因此如果不是通过MybatisSqlSessionFactoryBean而是原始mybatis构建方式构建的SqlSessionFactory会出现空指针问题。


public class MybatisSqlSessionFactoryBean {
    ...
	protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
	    ...
		GlobalConfigUtils.setGlobalConfig(targetConfiguration, this.globalConfig);
	}
}
上一篇:pysim-4-1.1.17 eUICC ISD-R commands


下一篇:墙绘交易平台设计:SpringBoot技术要点