MyBatis-Plus是一款非常好用的Mybatis插件,不需要使用xml,在这里就不说Mybatis-Plus的普通操作了,说下批量操作的原理。
一、批量操作的方式
Mybatis-Plus提供了批量操作的方式,就是updateBatch,insertBatch方法。使用方式如下:
BloodPressureReport report = new BloodPressureReport();
report.setOrderNoo(453496L);
report.setWeimaihao(34988340958L);
report.setId(43987958794069L);
List<BloodPressureReport> reports = new ArrayList<>();
reports.add(report);
reports.add(report);
boolean isUpdate = service.updateBatchById(reports);
二、执行结果
执行了批量操作后,控制台会打印执行结果
Time:0 ms - ID:com.ecarx.pointstore.mapper.BloodPressureReportMapper.updateById
Execute SQL:UPDATE blood_pressure_report SET weimaihao=34988340958, order_no=453496 WHERE id=43987958794069
Time:0 ms - ID:com.ecarx.pointstore.mapper.BloodPressureReportMapper.updateById
Execute SQL:UPDATE blood_pressure_report SET weimaihao=34988340958, order_no=453496 WHERE id=43987958794069
可以看到service.updateBatch其实是把批量操作分成两次执行了。其实最后是两次执行PrepareStatement的两次update方法。
三、调用方法
最后是调用了PreparedStatement的executeBatchSerially()方法。
/**
* Executes the current batch of statements by executing them one-by-one.
*
* @return a list of update counts
* @throws SQLException
* if an error occurs
*/
protected int[] executeBatchSerially(int batchTimeout) throws SQLException {
从注释可以看到批量修改确实也要一条条执行,但是批量插入呢?很明显,因为无法确定你要插入的字段是否是全字段插入,所以默认提供的方法肯定是单条插入的。这是最合适的做法。
四、怎么真正的批量执行
Mabatis的xml中写了
insert('a','b','c') values ('1','1','1'),('2','2','2');
其实是一条插入语句,是批量执行。update,和remove就不支持这种语法了。如果想让update,remove也批量,需要配置mysql连接参数。
如果想做到真正批量执行,需要调用prepareStatement的executeBatchedInserts()或者executePreparedBatchAsMultiStatement()方法,这就需要设置rewriteBatchedStatements为true。