MybaitsPlus拦截器使用

10

场景

动态表名拦截、分页拦截。

Code

package com.bjelu.itos.common.mybatisplus;

import cn.hutool.core.util.ReUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.commons.lang3.StringUtils;

@Configuration
public class MybatisPlusConfig {

    /***
     * 使用ThreadLocal将表名传进来 线程可能不会被销毁值可能不会回收 记得手动remove
     */
    public static ThreadLocal<String> tableNameLocal = new ThreadLocal<>();

    /**
     * 配置分页
     * 新的分页插件,一缓和二缓遵循mybatis的规则
     * 需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题
     * see {<https://mybatis.plus/guide/page.html>}
     *
     * @return PaginationInterceptor
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 动态表名拦截器
        interceptor.addInnerInterceptor(initDynamicTableNameInnerInterceptor());
        // 分页拦截器
        interceptor.addInnerInterceptor(initPaginationInterceptor());
        return interceptor;
    }

    /**
     * 初始化分页拦截器
     */
    private InnerInterceptor initPaginationInterceptor() {
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.POSTGRE_SQL);
        // 单页分页条数限制,默认不受限制
        paginationInnerInterceptor.setMaxLimit(-1L);
        // 溢出总页数后是否进行处理
        paginationInnerInterceptor.setOverflow(false);
        return paginationInnerInterceptor;
    }

    /**
     * 初始化动态表名拦截器
     */
    private InnerInterceptor initDynamicTableNameInnerInterceptor() {
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {

            String replaceTabName = tableNameLocal.get();
            tableNameLocal.remove();
            if (StringUtils.isEmpty(replaceTabName)) {
                return tableName;
            }
            //替换查询表前缀 带有指定模式的sql 比如chongqing.next_**** 取得 chongqing.   
            if (tableName.contains(".")) {
                String schema = ReUtil.replaceAll(tableName, "(.*)(\\\\.)(.*)", "$1$2");
                return schema + replaceTabName;
            } else {
                return replaceTabName;
            }
        });
        return dynamicTableNameInnerInterceptor;
    }
}

拦截器应用

/**
 * @author Ghost
 */
@Service
public class NextLineFlowServiceImpl
        extends ServiceImpl<NextLineFlowMapper, NextLineFlow>
        implements NextLineFlowService {

       @Autowired
    private NextLineFlowMapper nextLineFlowMapper;

    @Override
    public NextLineFlow sumFlowByLineNameAndTime(List<String> lineNames, Date startTime, Date endTime, String tabSuffix) {
        //设置表前缀
        MybatisPlusConfig.tableNameLocal.set(tabSuffix);
        return this.query()
                .select("linename", "SUM(entryflow) entryflow",
                        "SUM(exitflow) exitflow",
                        "SUM(transferinflow) transferinflow",
                        "SUM(transferoutflow) transferoutflow",
                        "SUM(passengerflow) passengerflow")
                .in("linename", lineNames)
                .ge("starttime", startTime)
                .le("endtime", endTime)
                .groupBy("linename")
                .one();

    }

    @Override
    public List<NextLineFlow> findByStartTimeGreaterThanEqualAndEndTimeLessThanEqualAndLineNameIn
            (Date startTime, Date endTime, List<String> stationNames, String tabName) {

        return this.lambdaQuery()
                .in(NextLineFlow::getLineName, stationNames)
                .ge(NextLineFlow::getStartTime, startTime)
                .le(NextLineFlow::getEndTime, endTime)
                .list();
    }

}