Mybatis Plus 自定义SqlInjector sql注入器

1、自定义sql注入器GeneralMybatisPlusSqlInjector

package com.javasgj.springboot.mybatisplus.config;

import java.util.List;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;

/**
 * 自定义sql注入器,增加通用方法
 */
public class GeneralMybatisPlusSqlInjector extends DefaultSqlInjector {
    @Override
    public List<AbstractMethod> getMethodList() {
        List<AbstractMethod> methodList = super.getMethodList();
        // 根据id更新所有数据
        methodList.add(new UpdateAllColumnById());
        return methodList;
    }
}

2、方法对应的实现类UpdateAllColumnById

package com.javasgj.springboot.mybatisplus.config;

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

import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

import com.baomidou.mybatisplus.annotation.FieldFill;
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.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;

/**
 * 根据id更新所有数据
 */
public class UpdateAllColumnById extends AbstractMethod {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        
        GeneralMybatisPlusSqlMethod sqlMethod = GeneralMybatisPlusSqlMethod.UPDATE_ALL_COLUMN_BY_ID;
        String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(),
            sqlSet(false, false, tableInfo, Constants.ENTITY_SPOT),
            tableInfo.getKeyColumn(), Constants.ENTITY_SPOT + tableInfo.getKeyProperty(),
            new StringBuilder("<if test=\"et instanceof java.util.Map\">")
                .append("<if test=\"et.MP_OPTLOCK_VERSION_ORIGINAL!=null\">")
                .append(" AND ${et.MP_OPTLOCK_VERSION_COLUMN}=#{et.MP_OPTLOCK_VERSION_ORIGINAL}")
                .append("</if></if>"));
        
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
    }

    @Override
    protected String sqlSet(boolean logic, boolean ew, TableInfo table, String prefix) {
        String newPrefix = prefix == null ? StringPool.EMPTY : prefix;
        String sqlScript = table.getFieldList().stream()
            .filter(i -> {
                return true;
            })
            .map(i -> {
                return this.getSqlSet(i, newPrefix);
            }).collect(joining(StringPool.NEWLINE));
            
        if (ew) {
            sqlScript += StringPool.NEWLINE;
            sqlScript += SqlScriptUtils.convertIf(SqlScriptUtils.unSafeParam(Constants.U_WRAPPER_SQL_SET),
                String.format("%s != null and %s != null", Constants.WRAPPER, Constants.U_WRAPPER_SQL_SET), false);
        }
        sqlScript = SqlScriptUtils.convertTrim(sqlScript, "SET", null, null, ",");
        return sqlScript;
    }
    
    public String getSqlSet(TableFieldInfo i, String prefix) {
        String newPrefix = prefix == null ? StringPool.EMPTY : prefix;
        String column = i.getColumn();
        String update = i.getUpdate();
        FieldFill fieldFill = i.getFieldFill();
        String el = i.getEl();
        
        // 默认: column=
        String sqlSet = column + StringPool.EQUALS;
        if (StringUtils.isNotEmpty(update)) {
            sqlSet += String.format(update, column);
        } else {
            sqlSet += SqlScriptUtils.safeParam(newPrefix + el);
        }
        sqlSet += StringPool.COMMA;
        if (fieldFill == FieldFill.UPDATE || fieldFill == FieldFill.INSERT_UPDATE) {
            // 不进行 if 包裹
            return sqlSet;
        }
        return sqlSet;
    }
}

参考其他基本方法的实现类源码如:UpdateById等等

3、MybatisPlus自定义SQL方法枚举类GeneralMybatisPlusSqlMethod

package com.javasgj.springboot.mybatisplus.config;

/**
 * MybatisPlus自定义SQL方法
 */
public enum GeneralMybatisPlusSqlMethod {
    
    /**
     * 修改
     */
    UPDATE_ALL_COLUMN_BY_ID("updateAllColumnById", "根据ID更新所有数据", "<script>\nUPDATE %s %s WHERE %s=#{%s} %s\n</script>");

    private final String method;
    private final String desc;
    private final String sql;

    GeneralMybatisPlusSqlMethod(String method, String desc, String sql) {
        this.method = method;
        this.desc = desc;
        this.sql = sql;
    }

    public String getMethod() {
        return method;
    }

    public String getDesc() {
        return desc;
    }

    public String getSql() {
        return sql;
    }
}

4、MybatisPlus配置类,加载自定义sql注入器

package com.javasgj.springboot.mybatisplus.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;

/**
 * MybatisPlus配置类
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 分页插件
     * 或者在mybatis-config.xml配置:
     *  <plugins>  
     *      <!-- mybatisplus分页拦截器 -->
     *      <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor">
     *      </plugin>  
     *  </plugins> 
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /**
     * 自定义sql注入器
     * 或者application.properties配置:
     * mybatis-plus.globalConfig.sqlInjector=com.javasgj.springboot.mybatisplus.config.GeneralMybatisPlusSqlInjector
     */
    @Bean
    public ISqlInjector iSqlInjector() {
        return new GeneralMybatisPlusSqlInjector();
    }

    /**
     * sql性能分析插件,输出sql语句及所需时间
     */
    /*@Bean
    @Profile({"dev","test"})// 设置 dev test 环境开启
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }*/
    
    /**
     * 乐观锁插件
     */
    /*@Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor(){
        return new OptimisticLockerInterceptor();
    }*/
}

5、自定义基础Mapper继承BaseMapper

package com.javasgj.springboot.mybatisplus.dao;

import org.apache.ibatis.annotations.Param;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;

public interface GeneralBaseMapper<T> extends BaseMapper<T> {

    /**
     * 根据id更新所有数据
     * @param entity
     * @return
     */
    int updateAllColumnById(@Param(Constants.ENTITY) T entity);
}

6、自定义基础service继承IService及实现类

package com.javasgj.springboot.mybatisplus.service;

import java.util.Collection;

import com.baomidou.mybatisplus.extension.service.IService;

public interface GeneralService<T> extends IService<T> {

    /**
     * 根据ID更新所有数据
     * @param entity
     * @return
     */
    boolean updateAllColumnById(T entity);
    
    /**
     * 根据ID批量更新所有数据
     * @param entityList
     * @return
     */
    default boolean updateAllColumnBatchById(Collection<T> entityList) {
        return updateAllColumnBatchById(entityList, 30);
    }
    
    /**
     * 根据ID批量更新所有数据
     * @param entityList
     * @param batchSize
     * @return
     */
    boolean updateAllColumnBatchById(Collection<T> entityList, int batchSize);
}

实现测试类

package com.javasgj.springboot.mybatisplus.service;

import java.util.Collection;

import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.session.SqlSession;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlHelper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javasgj.springboot.mybatisplus.config.GeneralMybatisPlusSqlMethod;
import com.javasgj.springboot.mybatisplus.dao.GeneralBaseMapper;

public class GeneralServiceImpl<M extends GeneralBaseMapper<T>, T> extends ServiceImpl<GeneralBaseMapper<T>, T> implements GeneralService<T> {

    /**
     * 获取SqlStatement
     *
     * @param sqlMethod
     * @return
     */
    protected String sqlStatement(GeneralMybatisPlusSqlMethod generalMybatisPlusSqlMethod) {
        return SqlHelper.table(currentModelClass()).getSqlStatement(generalMybatisPlusSqlMethod.getMethod());
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateAllColumnById(T entity) {
        return retBool(baseMapper.updateAllColumnById(entity));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateAllColumnBatchById(Collection<T> entityList, int batchSize) {
        if (CollectionUtils.isEmpty(entityList)) {
            throw new IllegalArgumentException("Error: entityList must not be empty");
        }
        int i = 0;
        String sqlStatement = sqlStatement(GeneralMybatisPlusSqlMethod.UPDATE_ALL_COLUMN_BY_ID);
        try (SqlSession batchSqlSession = sqlSessionBatch()) {
            for (T anEntityList : entityList) {
                MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
                param.put(Constants.ENTITY, anEntityList);
                batchSqlSession.update(sqlStatement, param);
                if (i >= 1 && i % batchSize == 0) {
                    batchSqlSession.flushStatements();
                }
                i++;
            }
            batchSqlSession.flushStatements();
        }
        return true;
    }
}

然后所有的mapper和servcie继承我们自定义扩展的基础mapper和service

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值