mybatis-plus 自定义sql

自定义首先继承于 DefaultSqlInjector 这个类 实现接口 getMethodList

package com.app.common.mybatis;
import com.app.common.mybatis.mysql.BatchInsert;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.springframework.beans.factory.annotation.Configurable;

import java.util.List;

/**
 *
 * @Description
 * @Datetime 2022/4/25 15:17
 * @Modified By
 */
@Configurable
public class CustomSqlInjector extends DefaultSqlInjector  {

	   @Override
	   public List<AbstractMethod> getMethodList (Class<?> mapperClass, TableInfo tableInfo) {
		      var methodList = super.getMethodList(mapperClass, tableInfo);
		      methodList.add(new BatchInsert());
		      methodList.add(new BatchUpdate());
		      return methodList;
	   }
}

具体实现方法是 继承AbstractMethod这个类
下边是一个批量插入自定义sql拼接类 这个批量插入工具类

package com.app.common.mybatis.mysql;

import com.app.common.enums.SqlMethodEnum;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

import java.util.Objects;
import java.util.function.Predicate;

import static java.util.stream.Collectors.joining;

/**
 * 
 * @Description
 * @Datetime 2022/4/25 15:19
 * @Modified By
 */
public class BatchInsert extends AbstractMethod {
	   /**
	    * 字段筛选条件
	    */
	   @Setter
	   @Accessors (chain = true)
	   private Predicate<TableFieldInfo> predicate;
	   
	   @Override
	   public MappedStatement injectMappedStatement (Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
		      KeyGenerator keyGenerator = NoKeyGenerator.INSTANCE;
		      SqlMethodEnum sqlMethod = SqlMethodEnum.BATCH_INSERT;
		      var columnScript = tableInfo.getFieldList().stream().map(s -> s.getColumn()).filter(Objects :: nonNull).collect(joining(DOT_NEWLINE));
		      String valuesScript = tableInfo.getFieldList().stream().map(s -> s.getInsertSqlProperty("list.")).filter(Objects :: nonNull).collect(joining(NEWLINE));
		      var valuesLenght =   valuesScript.length()- 1;
		      if(valuesScript.lastIndexOf(COMMA)==valuesLenght){
				valuesScript= valuesScript.substring(0,valuesLenght);
		     }
		      String keyProperty = null;
		      String keyColumn = null;
		      // 表包含主键处理逻辑,如果不包含主键当普通字段处理
		      if (StringUtils.isNotBlank(tableInfo.getKeyProperty())) {
				 if (tableInfo.getIdType() == IdType.AUTO) {
					    /* 自增主键 */
					    keyGenerator = Jdbc3KeyGenerator.INSTANCE;
					    keyProperty = tableInfo.getKeyProperty();
					    keyColumn = tableInfo.getKeyColumn();
				 } else {
					    if (null != tableInfo.getKeySequence()) {
						       keyGenerator = TableInfoHelper.genKeyGenerator(sqlMethod.getMethod(), tableInfo, builderAssistant);
						       keyProperty = tableInfo.getKeyProperty();
						       keyColumn = tableInfo.getKeyColumn();
					    }
				 }
		      }
		      String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), columnScript, valuesScript);
		      SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
		      return this.addInsertMappedStatement(mapperClass, modelClass, SqlMethodEnum.BATCH_INSERT.getMethod(), sqlSource, keyGenerator, keyProperty, keyColumn);
	   }
}


自定义基础mapper 类所有mapper 都继承这个mapper


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @Description
 * @Datetime 2022/4/25 17:01
 * @Modified By
 */
public interface IBaseMapper <T> extends BaseMapper<T> {
	   void batchInsert(@Param ("list") List<T> list);
	   
	   void batchUpdate(@Param("list") List<T> list);
}

最后一步 把这个类加入 配置类中

package com.app.validation.service.config;

import com.app.common.mybatis.CustomSqlInjector;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Mybatis配置
 */
@Configuration
public class MybatisConfig {
    /**
     * 3.4.0 以后的配置方式
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 乐观锁
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        // 分页配置
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

    /**
     * 自定义sql注入器
     */
    @Bean
    public ISqlInjector iSqlInjector() {
        return new CustomSqlInjector();
    }
}
posted @   wczhw  阅读(2473)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示