一.背景
最近mybatis-plus框架的更新,让我们基础开发中如虎添翼。其中基本的增删改查,代码生成器想必大家用着那叫一个爽。本人在使用中,也遇到一些坑。比如savebatch,saveorupdatebatch,看着这不是批量新增,批量新增或更新嘛,看着api进行开发,感觉也太好用啦。开发完一测试,速度跟蜗牛一样,针对大数据量真是无法忍受。在控制台上发现,怎么名义上是批量插入,还是一条一条的进行插入,难怪速度龟速。
二.解决办法
查阅网上资料,大体有两种解决方案:
(1).使用mybatis的xml,自己进行sql语句编写。该方法一个缺点是如果表的字段较多,有个几十个字段,写批量新增,批量新增修改的sql语句真是个噩梦。
INSERT INTO t
(id, age)
VALUES
(3, 28),
(4, 29)
ON DUPLICATE KEY UPDATE
id = VALUES(id),
age = VALUES(age);
(2)mybatis-plus 新添加了一个sql注入器,通过sql注入器可以实现批量新增,批量新增修改功能。一次注入,随时使用,使用极其方便。缺点就是项目启动时候,会进行sql注入器注册,稍微影响启动速度。
三.sql注入器实现批量更新,批量新增或更新功能
(1)自定义mapper接口,继承BaseMapper,定义实现的方法。
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface RootMapper<T> extends BaseMapper<T> {
int insertBatch(@Param("list") List<T> list);
int mysqlInsertOrUpdateBath(@Param("list") List<T> list);
}
(2)批量插入、批量新增或更新具体方法实现
批量插入具体方法实现如下:
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
@Slf4j
public class InsertBatchMethod extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
final String sql = "<script>insert into %s %s values %s</script>";
final String fieldSql = prepareFieldSql(tableInfo);
final String valueSql = prepareValuesSql(tableInfo);
final String sqlResult = String.format(sql, tableInfo.getTableName(), fieldSql, valueSql);
log.debug("sqlResult----->{}", sqlResult);
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
// 第三个参数必须和RootMapper的自定义方法名一致
return this.addInsertMappedStatement(mapperClass, modelClass, "insertBatch", sqlSource, new NoKeyGenerator(), null, null);
}
private String prepareFieldSql(TableInfo tableInfo) {
StringBuilder fieldSql = new StringBuilder();
fieldSql.append(tableInfo.getKeyColumn()).append(",");
tableInfo.getFieldList().forEach(x -> {
fieldSql.append(x.getColumn()).append(",");
});
fieldSql.delete(fieldSql.length() - 1, fieldSql.length());
fieldSql.insert(0, "(");
fieldSql.append(")");
return fieldSql.toString();
}
private String prepareValuesSql(TableInfo tableInfo) {
final StringBuilder valueSql = new StringBuilder();
valueSql.append("<foreach collection=\"list\" item=\"item\" index=\"index\" open=\"(\" separator=\"),(\" close=\")\">");
valueSql.append("#{item.").append(tableInfo.getKeyProperty()).append("},");
tableInfo.getFieldList().forEach(x -> valueSql.append("#{item.").append(x.getProperty()).append("},"));
valueSql.delete(valueSql.length() - 1, valueSql.length());
valueSql.append("</foreach>");
return valueSql.toString();
}
}
批量插入或更新具体方法如下:
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.springframework.util.StringUtils;
public class MysqlInsertOrUpdateBath extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
final String sql = "<script>insert into %s %s values %s ON DUPLICATE KEY UPDATE %s</script>";
final String tableName = tableInfo.getTableName();
final String filedSql = prepareFieldSql(tableInfo);
final String modelValuesSql = prepareModelValuesSql(tableInfo);
final String duplicateKeySql =prepareDuplicateKeySql(tableInfo);
final String sqlResult = String.format(sql, tableName, filedSql, modelValuesSql,duplicateKeySql);
//System.out.println("savaorupdatesqlsql="+sqlResult);
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
return this.addInsertMappedStatement(mapperClass, modelClass, "mysqlInsertOrUpdateBath", sqlSource, new NoKeyGenerator(), null, null);
}
private String prepareDuplicateKeySql(TableInfo tableInfo) {
final StringBuilder duplicateKeySql = new StringBuilder();
if(!StringUtils.isEmpty(tableInfo.getKeyColumn())) {
duplicateKeySql.append(tableInfo.getKeyColumn()).append("=values(").append(tableInfo.getKeyColumn()).append("),");
}
tableInfo.getFieldList().forEach(x -> {
duplicateKeySql.append(x.getColumn())
.append("=values(")
.append(x.getColumn())
.append("),");
});
duplicateKeySql.delete(duplicateKeySql.length() - 1, duplicateKeySql.length());
return duplicateKeySql.toString();
}
private String prepareFieldSql(TableInfo tableInfo) {
StringBuilder fieldSql = new StringBuilder();
fieldSql.append(tableInfo.getKeyColumn()).append(",");
tableInfo.getFieldList().forEach(x -> {
fieldSql.append(x.getColumn()).append(",");
});
fieldSql.delete(fieldSql.length() - 1, fieldSql.length());
fieldSql.insert(0, "(");
fieldSql.append(")");
return fieldSql.toString();
}
private String prepareModelValuesSql(TableInfo tableInfo){
final StringBuilder valueSql = new StringBuilder();
valueSql.append("<foreach collection=\"list\" item=\"item\" index=\"index\" open=\"(\" separator=\"),(\" close=\")\">");
if(!StringUtils.isEmpty(tableInfo.getKeyProperty())) {
valueSql.append("#{item.").append(tableInfo.getKeyProperty()).append("},");
}
tableInfo.getFieldList().forEach(x -> valueSql.append("#{item.").append(x.getProperty()).append("},"));
valueSql.delete(valueSql.length() - 1, valueSql.length());
valueSql.append("</foreach>");
return valueSql.toString();
}
}
(3)sql注入器实现
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import java.util.List;
public class CustomizedSqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
methodList.add(new InsertBatchMethod());
methodList.add(new UpdateBatchMethod());
methodList.add(new MysqlInsertOrUpdateBath());
return methodList;
}
}
(4)在自己想使用的mapper上继承自定义的mapper.
import com.sy.adp.common.mybatisPlusExtend.RootMapper;
import com.sy.adp.flowfull.entity.InfMpmPds;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
@Component
public interface InfMpmPdsMapper extends RootMapper<InfMpmPds> {
IPage<InfMpmPds> selectPageList(Page page, @Param("infMpmPds") InfMpmPds infMpmPds);
}
(5)在controller或serviceImpi中引入mapper,使用自定义的方法。
>>>>>>>>>>>>>>>>>>>>引入mapper>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>方法使用>>>>>>>>>>>>
完成上述步骤,就可以运行项目进行测试看看,数据提升是不是几个数量级。
到此这篇关于mybatis-plus 关于savebatch,saveorupdatebatch遇到的坑及解决办法的文章就介绍到这了,更多相关mybatis-plus savebatch,saveorupdatebatch内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!