当前位置: 首页 > news >正文

扩展BaseMapper类

扩展mybatis-plus的BaseMapper类

  • insertBatch
  • insertIfNotExists

mp的BaseMapper只提供了简单的增删改查方法,一些复杂点的操作没有提供,或是在IService类中提供。如果想要直接通过mapper类调用这些方法,可以通过扩展BaseMapper来使其获取新的功能。

insertBatch

扩展一个批量插入insertBatch的方法。

  1. 定义SqlInjector类,扩展功能
public class ExpandSqlInjector extends DefaultSqlInjector {@Overridepublic List<AbstractMethod> getMethodList(Class<?> mapperClass) {List<AbstractMethod> methodList = super.getMethodList(mapperClass);methodList.add(new InsertBatchMethod());methodList.add(new InsertIfNotExistsMethod());return methodList;}/*** 批量插入方法*/public static class InsertBatchMethod extends AbstractMethod {@Overridepublic MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {String sql = "<script>INSERT INTO %s (%s) VALUES %s";List<String> columnList = new ArrayList<>();List<String> propertyList = new ArrayList<>();if (tableInfo.havePK() && !AUTO.equals(tableInfo.getIdType())) {columnList.add(tableInfo.getKeyColumn());propertyList.add(tableInfo.getKeyProperty());}// getFiledList等方法获取的内容会自动根据@TableField相关配置而改变for (TableFieldInfo fieldInfo : tableInfo.getFieldList()) {columnList.add(fieldInfo.getColumn());propertyList.add(fieldInfo.getProperty());}String columns = String.join(",", columnList);String values = "<foreach collection='list' item='item' separator=','>" +"(#{item." + String.join("},#{item.", propertyList) + "})" +"</foreach></script>";String sqlResult = String.format(sql, tableInfo.getTableName(), columns, values);SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);return getMappedStatement(this::addInsertMappedStatement, mapperClass, "insertBatch", modelClass, tableInfo, sqlSource, "");}}private static MappedStatement getMappedStatement(MappedStatementMethod method, Class<?> mapperClass, String id, Class<?> modelClass, TableInfo tableInfo, SqlSource sqlSource, String prefix) {// 根据@TableId注解自动设置KeyGeneratorKeyGenerator keyGenerator = NoKeyGenerator.INSTANCE; // 默认值String keyColumn = null;String keyProperty = null;// 如果表有主键字段if (tableInfo.havePK()) {keyColumn = tableInfo.getKeyColumn();keyProperty = prefix + tableInfo.getKeyProperty();// 根据主键类型设置,INPUT、NONE:NoKeyGenerator,ASSIGN_ID, ASSIGN_UUID等策略,Java层面生成,不需要数据库生成if (AUTO.equals(tableInfo.getIdType())) {keyGenerator = Jdbc3KeyGenerator.INSTANCE;}}// 这里的keyGenerator与实际sql语句无关,是否插入id取决你构造的sql语句return method.accept(mapperClass, modelClass, id, sqlSource, keyGenerator, keyProperty, keyColumn);}@FunctionalInterfacepublic interface MappedStatementMethod {MappedStatement accept(Class<?> mapperClass, Class<?> parameterType, String id, SqlSource sqlSource, KeyGenerator keyGenerator, String keyProperty, String keyColumn);}
}
  1. 配置SqlInjector:在mp的配置类中(也可以通过yml文件配置)
@Bean
public ExpandSqlInjector expandSqlInjector() {return new ExpandSqlInjector();
}
  1. 具体mapper类加上insertBatch方法;或定义一个新的BaseMapper,让其继承BaseMapper(推荐后者,可以统一配置)

实际通过前面二步,生成的BaseMapper代理类已经有了扩展的方法,这一步了是为了让接口也拥有扩展方法。

public interface AppMapper<T> extends BaseMapper<T> {/*** 批量插入* @param list 实体列表* @return 插入条数*/int insertBatch(List<T> list);
}

insertIfNotExists

扩展一个不存在则插入insertIfNotExists的方法。

  1. ExpandSqlInjector类中添加以下内容
/*** 如果满足条件的记录不存在才插入*/
public static class InsertIfNotExistsMethod extends AbstractMethod {@Overridepublic MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {// 动态生成 SQLString sql = "<script>INSERT INTO %s (%s) " +"SELECT %s FROM dual " +"WHERE NOT EXISTS (" +"   SELECT 1 FROM %s ${ew.customSqlSegment}" +")</script>";// 1. 插入的字段列表(会自动加上if标签,根据类型添加相关的非空判断,最后一个字段会多个逗号)String insertColumns = tableInfo.getAllInsertSqlColumnMaybeIf("entity.");insertColumns = SqlScriptUtils.convertTrim(insertColumns, null, null, null, ",");// 2. 插入的值(会自动加上if标签,根据类型添加相关的非空判断,最后一个值会多个逗号)String insertValues = tableInfo.getAllInsertSqlPropertyMaybeIf("entity.");insertValues = SqlScriptUtils.convertTrim(insertValues, null, null, null, ",");String tableName = tableInfo.getTableName();String sqlResult = String.format(sql, tableName, insertColumns, insertValues, tableName);SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);return getMappedStatement(this::addInsertMappedStatement, mapperClass, "insertIfNotExists", modelClass, tableInfo, sqlSource, "entity.");}
}
  1. AppMapper类里添加以下内容:
/*** 插入,如果满足指定条件的记录已存在则忽略* @param entity 插入的实体类实例* @param ew 条件对象*/
int insertIfNotExists(@Param("entity") T entity, @Param(WRAPPER) Wrapper<T> ew);
http://www.dtcms.com/a/431175.html

相关文章:

  • 秦皇岛建设部网站工程建设信息都在哪个网站发布
  • 多模态分类:图文结合的智能识别与代码实战
  • UE5 - C++项目基础
  • Word和WPS文字表格内的文字无法垂直居中?这样设置
  • 平台设计网站公司电话号码网站建设最好用什么语言
  • 【数组倍数去重】2022-11-26
  • vite插件的使用
  • 惠州网站建设是什么渠道查官网
  • 个人做网站有什么条件网站备案信息填写
  • 自建网站代理服务器深圳建设网站推荐
  • 2025 AI 图景:从工具革命到生态重构的生存逻辑
  • 基于人工智能的电信经营分析系统架构研究
  • 环保部网站建设项目验收方案上海哪家做公司网站
  • RoCE V2 深度解析
  • PostgreSQL视图不存数据?那它怎么简化查询还能递归生成序列和控制权限?
  • 小马厂网站建设商业信息发布平台
  • 随机过程:从理论到Python实践
  • 做国外网站用什么颜色建站行业的发展前景
  • Google Earth Pro(谷歌地球)2025年7月大陆版安装教程
  • C++与Open CASCADE中的STEP格式处理:从基础到高级实践
  • 【大模型】ubuntu搭建ollama 使用ollama本地部署deepseek qwen等大模型
  • Win32 托盘图标弹出菜单使用
  • MATLAB中SIL 和 PIL 仿真
  • 基于NUC和STM32F103的无人车
  • wordpress网站的配置文件进出口外贸公司名字
  • 【报错】qt.qpa.plugin: Could not find the Qt platform plugin “windows“ in ““
  • 彩票网站给实体店做代销个人网站设计论文道客巴巴
  • 学校网站建设注意点美妆网站设计模板
  • 【算法训练营Day28】动态规划part4
  • PandasAI:ChatBI的极简上手版学习(一)