使用过mybatis-plus的朋友 应该都知道BaseMapper未提供批量插入接口,但是在com.baomidou.mybatisplus.service.IService中提供了 但是运行日志却是一条一条的执行 优化代码如下 让你实现真正意义上的批量操作
添加批量新增和更新类
批量插入方法实现
首先来看一段批量新增的代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bvp.wms.order.web.mapper.InBoundOrderReportFileMapper">
<insert id="insertAll">
INSERT INTO in_bound_order_report_file_info
VALUES
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.id},
#{item.inBoundOrderEnclosureId},
#{item.reportFileUrl},
#{item.createdBy},
#{item.createdTime},
#{item.lastUpdatedBy},
#{item.lastUpdatedTime},
#{item.sts},
#{item.tenantId}
)
</foreach>
</insert>
</mapper>
我们只需要将这条sql使用代码拼接出来就好
package com.bvp.wms.db.mybatis;
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;
/**
* @description: 批量插入方法实现
* @Author:
* @NAME: InsertBatchMethod
* @date: 2022/8/23 9:26
*/
@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);
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();
}
}
批量更新方法实现,条件为主键,选择性更新
更新方法和新增一样 拼接sql
package com.bvp.wms.db.mybatis;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
/**
* @description: 批量更新方法实现,条件为主键,选择性更新
* @Author:
* @NAME: UpdateBatchMethod
* @date: 2022/8/23 9:27
*/
@Slf4j
public class UpdateBatchMethod extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
String sql = "<script>\n<foreach collection=\"list\" item=\"item\" separator=\";\">\nupdate %s %s where %s=#{%s} %s\n</foreach>\n</script>";
String additional = tableInfo.isWithVersion() ? tableInfo.getVersionFieldInfo().getVersionOli("item", "item.") : "" + tableInfo.getLogicDeleteSql(true, true);
String setSql = sqlSet(tableInfo.isWithLogicDelete(), false, tableInfo, false, "item", "item.");
String sqlResult = String.format(sql, tableInfo.getTableName(), setSql, tableInfo.getKeyColumn(), "item." + tableInfo.getKeyProperty(), additional);
//log.debug("sqlResult----->{}", sqlResult);
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
// 第三个参数必须和RootMapper的自定义方法名一致
return this.addUpdateMappedStatement(mapperClass, modelClass, "updateBatch", sqlSource);
}
}
添加自定义方法SQL注入器
package com.bvp.wms.db.mybatis;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import java.util.List;
/**
* @description: SQL注入器
* @Author:
* @NAME: CustomizedSqlInjector
* @date: 2022/8/23 9:29
*/
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());
return methodList;
}
}
注入配置
package com.bvp.wms.mail.web.common.config;
import com.bvp.wms.db.mybatis.CustomizedSqlInjector;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @description: 注入配置
* @Author:
* @NAME: MyBatisPlusConfig
* @date: 2022/8/23 9:30
*/
@MapperScan("com.bvp.wms.mail.web.mapper")//注意此处是mapper对应的包名
@Configuration
public class MyBatisPlusConfig {
@Bean
public CustomizedSqlInjector customizedSqlInjector() {
return new CustomizedSqlInjector();
}
}
添加通用mapper
package com.bvp.wms.db.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* mapper 父类,注意这个类不要让 mp 扫描到!!
* @author communication
*/
public interface SuperMapper<T> extends BaseMapper<T> {
// 这里可以放一些公共的方法
/**
* 自定义批量插入
* 如果要自动填充,@Param(xx) xx参数名必须是 list/collection/array 3个的其中之一
*/
int insertBatch(@Param("list") List<T> list);
/**
* 自定义批量更新,条件为主键
* 如果要自动填充,@Param(xx) xx参数名必须是 list/collection/array 3个的其中之一
*/
int updateBatch(@Param("list") List<T> list);
}
这样就能一次执行 发送sql请求的时间节约了
不能飞的猪就仅仅是猪