mybatis-plus 提供了根据id批量更新和修改的方法,这个大家都不陌生 但是当表没有id的时候怎么办
- 方案一: 手写SQL
- 方案二: 手动获取SqlSessionTemplate 就是把mybatis plus 干的事自己干了
- 方案三 : 重写 executeBatch 方法
- 结论:
mybatis-plus 提供了根据id批量更新和修改的方法,这个大家都不陌生 但是当表没有id的时候怎么办)
方案一: 手写SQL
- 这个就不说了,就是因为不想手写SQL 所以才有这篇博客
方案二: 手动获取SqlSessionTemplate 就是把mybatis plus 干的事自己干了
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH,false);
static final BATCH_SIZE = 1000;
XxxMapper xxMapper = session.getMapper(XxxMapper.class);
int size = updateList.size();
try {
for(int i=0; i < size; i++) {
xxMapper.updateByXxx(updateList.get(i));
if(i % BATCH_SIZE == 0 || i == size-1){
session.commit();
session.clearCache();
}
}
}catch (Exception e) {
session.rollback();
} finally {
session.close();
}
方案三 : 重写 executeBatch 方法
@Transactional(rollbackFor = Exception.class)
@Override
public boolean updateBatchById(Collection<T> entityList, int batchSize) {
String sqlStatement = getSqlStatement(SqlMethod.UPDATE_BY_ID);
return executeBatch(entityList, batchSize, (sqlSession, entity) -> {
MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
param.put(Constants.ENTITY, entity);
sqlSession.update(sqlStatement, param);
});
}
- mybatis plus 的 executeBatch
- 参考 mybatis plus 的updateBatchById 方法.
- 调用处:
List<String> deleteList = new ArrayList<>();
dao.batchDelete(deleteList, delete -> new QueryWrapper<String>().eq("xx", delete));
List<OBJ> updateList = new ArrayList<>();
dao.batchUpdate(updateList, update -> new LambdaQueryWrapper<OBJ>()
.eq(OBJ::getProductId, update.getProductId()));
boolean batchUpdate(List<OBJ> updateList, Function<OBJ, LambdaQueryWrapper> queryWrapperFunction);
boolean batchDelete(List<String> deleteList, Function<String, QueryWrapper> queryWrapperFunction);
@Override
public boolean batchUpdate(List<OBJ> entityList, Function<OBJ, LambdaQueryWrapper> function) {
return this.executeBatch(entityList, DEFAULT_BATCH_SIZE, (sqlSession, entity) -> {
ParamMap param = new ParamMap();
param.put(Constants.ENTITY, entity);
param.put(Constants.WRAPPER, function.apply(entity));
sqlSession.update(this.getSqlStatement(SqlMethod.UPDATE), param);
});
}
@Override
public boolean batchDelete(List<String> deleteList, Function<String, QueryWrapper> function) {
return this.executeBatch(deleteList, DEFAULT_BATCH_SIZE, (sqlSession, entity) -> {
ParamMap param = new ParamMap();
param.put(Constants.ENTITY, entity);
param.put(Constants.WRAPPER, function.apply(entity));
sqlSession.delete(this.getSqlStatement(SqlMethod.DELETE), param);
});
}
结论:
- 这种写法其实批量的效率还是比较慢的,如果对性能没有要求,并且还不想手写SQL的,可以试一试.