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);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值