自学内容网 自学内容网

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);
}
}

原文地址:https://blog.csdn.net/u012794781/article/details/142515358

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!