使用mybatis的批处理功能,实现批量根据id更新功能

mybatis 批处理使用示例

​ mybatis预先已经帮我们集成了批量操作sql的功能,但是在和其他人交流的过程中,发现有很多人可能还不知道,所以来写几个例子,示范一下


使用批处理功能的准备工作

要使用mybatis的批处理功能,首先我们开启mysql驱动器自身对批量语句的优化,很简单,在数据库连接上追加&rewriteBatchedStatements=true就好了。(增加了该选项,驱动器会自动对批量sql进行转换,提高执行效率,但是要注意低版本的mysql-connector-java不支持该选项)

其次在代码中要能获取到一个mybatis的SqlSessionFactory,用于开启批处理操作。
目前,使用最广泛的基本上都已经是java config配置了,配置示例如下

@Configuration
@MapperScan("com.xx.xx.dal.mapper")
public class MybatisConfig {
    
    

	@Bean("mybatisSqlSession")
	public SqlSessionFactory sqlSessionFactory(@Qualifier(value = "dataSource") DataSource dataSource) throws Exception {
    
    
		SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
		sqlSessionFactory.setDataSource(dataSource);
		sqlSessionFactory.setTypeAliasesPackage("com.xx.xx.dal.entity");
		// 加载xml文件
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		sqlSessionFactory.setMapperLocations(resolver.getResources("classpath*:/mapper/**/*.xml"));

		SqlSessionFactory sqlSession = sqlSessionFactory.getObject();
		org.apache.ibatis.session.Configuration configuration =  sqlSession.getConfiguration();
		configuration.setMapUnderscoreToCamelCase(true);
		return sqlSessionFactory.getObject();
	}
}

经过该项配置后,我们就可以在任意地方使用spring的依赖注入功能,获取到配置好的SqlSessionFactory了

	@Autowired
	private SqlSessionFactory mybatisSqlSession;

根据id批量更新数据操作示例

根据id批量更新,其实也算是一个常见的业务操作,如果用单纯拼sql + foreach的方式去实现它,我个人感觉是很难受。。。
于是才不断的寻找怎么能比较方便的实现批量执行,所以才有了本篇文章。
在mybatis中使用开启批处理能力,只需要获取到一个批处理的session就可以了,十分的简单,代码示例如下

	try (SqlSession batchSession = mybatisSqlSession.openSession(ExecutorType.BATCH)) {
    
    
		ShengxiangOrderExtMapper orderExtMapper = batchSession.getMapper(ShengxiangOrderExtMapper.class);
		for (ShengxiangOrderDO order : updateOrderList) {
    
    
			orderExtMapper.updateByPrimaryKeySelective(order);
		}

		batchSession.commit();
	}
  1. 首先用SqlSessionFactory开启一个批处理模式的SqlSession — mybatisSqlSession.openSession(ExecutorType.BATCH)。
  2. 用该SqlSession去获取你要操作的dao mapper接口,这里注意一点,要使用批处理,只能通过该SqlSession去一个个获取mapper — batchSession.getMapper(ShengxiangOrderExtMapper.class)。
  3. 然后,你就可以像平常一样,使用mybatis一样操作mapper就好了,我这里是for循环执行单个的根据id更新数据方法。
  4. 当你要执行的批处理都做完以后,重点来了,使用SqlSession.commit() 进行提交你的批处理操作,这样一个批处理操作就走完了。
  5. 记得手动获取SqlSession的话,要自己关闭连接,我这里用的try with resource自动关闭的。

个人感觉这么使用批处理,比自己拼sql强多了~

猜你喜欢

转载自blog.csdn.net/lvqinglou/article/details/114823131