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