批量新增:

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 {@Overridepublic 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();}
}

批量修改:

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;/*** 重写批量修改*/
@Slf4j
public class UpdateBatchMethod extends AbstractMethod {@Overridepublic 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.isLogicDelete(), 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注入器:

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;import java.util.List;public class CustomizedSqlInjector extends DefaultSqlInjector {/*** SQL注入器*/@Overridepublic List<AbstractMethod> getMethodList(Class<?> mapperClass) {List<AbstractMethod> methodList = super.getMethodList(mapperClass);methodList.add(new InsertBatchMethod());methodList.add(new UpdateBatchMethod());return methodList;}
}

配置MyBatisPlusConfig:

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.MybatisMapWrapperFactory;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.Date;@Configuration
@MapperScan("com.assessment.score.mapper")
public class MybatisPlusConfig implements MetaObjectHandler {@Beanpublic PaginationInterceptor paginationInterceptor() {return new PaginationInterceptor();}@Beanpublic ConfigurationCustomizer mybatisConfigurationCustomizer(){return configuration -> configuration.setObjectWrapperFactory(new MybatisMapWrapperFactory());}@Beanpublic CustomizedSqlInjector customizedSqlInjector() {return new CustomizedSqlInjector();}
}

创建批量新增和修改的Mapper接口:

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;import java.util.List;//要继承BaseMapper
public interface RootMapper<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);
}

最后再让原来的mapper都继承RootMapper:

import com.assessment.score.entity.AssessPeopleScore;
import org.springframework.stereotype.Component;/*** <p>*  Mapper 接口* </p>** @author LiangZhongHao* @since 2022-06-08*/
@Component
public interface AssessPeopleScoreMapper extends RootMapper<AssessPeopleScore> {}

Service层直接引入mapper调用即可:
以下是我个人的业务场景:

@Autowired
private AssessPeopleScoreMapper peopleScoreMapper ;@Override
public int insert(List<PopPersonnel > peoples){for (PopPersonnel p :peoples){AssessPeopleScore ap = new AssessPeopleScore();ap.setPopName(p.getPopName());ap.setPopType(p.getIdentity());ap.setPopId(p.getPopId());ap.setGw(p.getGw());ap.setAssessOfId(assessOfId);ap.setSort(sort);list.add(ap);}peopleScoreMapper .insertBatch(list);
}

注*:俺只是搬运 并非原创…原创俺找不到了…在这里就想给自己的开发做个笔记~

Mybatis Plus重写批量新增和批量删除相关推荐

  1. mybatis批量新增和批量更新的效率对比

    今天,为了更多了解下,mybatis批量新增和批量更新在simple/batch模式 + MySQL的rewriteBatchedStatements下效率有什么区别,做了一次实验. 实验结果,让人意 ...

  2. Mybatis-plugs 批量新增及批量修改、IN、CASE WHEN操作

    1.1 基本介绍 Mybatis-plugs 批量新增及批量修改.IN.CASE WHEN 查询,简单,适用,最近用到了,那就留下点痕迹,免得下次用到再去找 <foreach> 标签里面的 ...

  3. MyBatis + Oracle 实现批量新增和批量修改

    MyBatis + Oracle 实现批量新增(基于序列化自增长主键) mapper 接口 void batchInsert(List<ASingleProject> list); map ...

  4. orcal 批量新增,批量更新多条件

    批量新增 <insert id="savePatientEmr" parameterType="java.util.List" useGeneratedK ...

  5. mysql不存在就批量新增_mysql批量插入,存在则修改,不存在则插入

    批量插入,存在则修改,不存在则插入 INSERT INTO 表名 (字段1,字段2,字段3,字段4) VALUES (字段1值,字段2值,字段3值,字段4值) ON DUPLICATE KEY UPD ...

  6. JAVA 之POI导入批量新增、批量检查、日志记录、失败原因、失败条数、数据库映射

    前言 欢迎大家来到我的博客,请各位看客们点赞.收藏.关注三连! 欢迎大家关注我的知识库,Java之从零开始·语雀 你的关注就是我前进的动力! CSDN专注于问题解决的博客记录,语雀专注于知识的收集与汇 ...

  7. mybatis-plus的批量新增/批量更新以及问题

    批量新增/删除 1.代码中foreach insert/update 2.多线程foreach insert/update 3.mybatis xml中foreach 4.通过自定义 SQL注入器扩展 ...

  8. mybatis mysql 批量更新_mysql批量update更新,mybatis中批量更新操作

    在日常开发中,有时候会遇到批量更新操作,这时候最普通的写法就是循环遍历,然后一条一条地进行update操作.但是不管是在服务端进行遍历,还是在sql代码中进行遍历,都很耗费资源,而且性能比较差,容易造 ...

  9. 基于ruoyi+vue+elementUI实现列表,新增,附件上传,tab+springBoot+mybatis+oracle序列+批量新增

    基于ruoyi+vue+elementUI实现列表,新增,附件上传,tab+springBoot+mybatis+oracle序列+批量新增 页面效果 列表页面 新增页面 详情页面 代码实现 列表+新 ...

最新文章

  1. Vue 过渡组件,可实现组件或者页面的动画过渡或者css过渡
  2. ajax返回去掉引号,为什么我的服务器代码ajax调用返回一个用双引号括起来的响应?...
  3. python输入多行字符串_python中怎么输入多行字符串
  4. php错误拦截机制,php拦截异常怎么写-PHP问题
  5. H264 RTP头分析
  6. BDD怎样帮助你解决沟通问题并增进协作
  7. 大学计算机课感悟100字,停课不停学的心得100字 停课不停学的感想
  8. ByteBuffer 转 InputStream
  9. oracle中job的retry次数,有大佬帮忙看下我安装过程中到底出啥问题了么..
  10. 超级实用的浏览器插件
  11. java 解析umd文件_Javascript模块化编程之CommonJS,AMD,CMD,UMD模块加载规范详解
  12. 从零开始学编程——环境配置
  13. codeforces 697C Lorenzo Von Matterhorn(二叉树LCA)
  14. Transformer课程 业务对话机器人Rasa 3.x 生成自然语言理解NLU数据
  15. 科大讯飞股价暴跌趋势不明,语音交互产业风险巨大吗?
  16. codecombat计算机科学入门五(python)
  17. 学计算机要学好数学吗,学好数学对计算机专业重要吗?
  18. (十八)师大放假了 - 7
  19. Java Missing method body, or declare abstract
  20. Unity中替换模型的方法

热门文章

  1. PHPExcel报“Formula Error: An unexpected error occured”
  2. matlab中文help,matlab中文帮助文档.pdf
  3. 小咖→殿堂,黑客等级划分
  4. 我的专业我的梦作文计算机,我的世界,我的梦作文500字
  5. MFC Web浏览器
  6. GoEasy,适用于多种前端框架,即时通讯技术
  7. python中定义一个学生类_python3 class类 练习题
  8. 使用lvgl时出现_lv_inv_area: detected modifying dirty areas in render (in lv_refr.c line #错误时如何解决
  9. 手机端MUI---html5框架
  10. 【C/C++ Windows编程】Windows系统消息、Qt消息事件、linux下kill信号