返回顶部
首页 > 资讯 > 后端开发 > Python >Mybatis框架中Interceptor接口的使用说明
  • 430
分享到

Mybatis框架中Interceptor接口的使用说明

2024-04-02 19:04:59 430人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

目录mybatis Interceptor接口的使用测试中使用的config文件内容如下在配置文件中配置了一个Interceptor的实现类Interceptor修改执行sql及传入

Mybatis Interceptor接口的使用

关于Mybatis中插件的声明需要在configuration的配置文件中进行配置,配置文件的位置使用configLocation属性指定。

测试中使用的config文件内容如下


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "Http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--plugins插件之 分页拦截器  -->
    <plugins>
        <plugin interceptor="com.interceptors.LogInterceptor" ></plugin>
    </plugins>
</configuration>

在配置文件中配置了一个Interceptor的实现类

LogInterceptor的代码如下:


public class LogInterceptor implements Interceptor{
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("LogInterceptor : intercept");
        return null;
    }
    @Override
    public Object plugin(Object target) {
        if(target instanceof StatementHandler){
            RoutingStatementHandler handler = (RoutingStatementHandler)target;
            //打印出当前执行的sql语句
            System.out.println(handler.getBoundSql().getSql());
        }
        return target;
    }
    @Override
    public void setProperties(Properties properties) {
        System.out.println("LogInterceptor : setProperties");
    }
}

在工程的配置文件中,在配置SqlSessionFactoryBean时需要指明config配置文件的位置,配置文件如下:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <bean id="user1" class="com.beans.User">
        <property name="userName" value="zhuyuqiang"/>
    </bean>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="name" value="Mysql"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/world"/>
        <property name="username" value="root"/>
        <property name="passWord" value="zh4y4q5ang"/>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:mybatis
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
}
)
public class ParamInterceptor implements Interceptor {
    private final static Pattern DW_DIMCOMPANY = Pattern.compile("dw_dimcompany", Pattern.CASE_INSENSITIVE);
    private final static String REPLACE_TXT = "(select * from dw_dimcompany where cisdel = '0' and START_PERIOD <= ? and END_PERIOD > ?)";
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];
        Executor executor = (Executor) invocation.getTarget();
        CacheKey cacheKey;
        BoundSql boundSql;
        if(args.length == 4){
            boundSql = ms.getBoundSql(parameter);
        } else {
            boundSql = (BoundSql) args[5];
        }
        //获取sql语句,使用正则忽略大小写匹配
        String sql = boundSql.getSql();
        Matcher matcher = DW_DIMCOMPANY.matcher(sql);
        //没有需要替换的表名则放行
        if(!matcher.find()){
            return invocation.proceed();
        }
       //收集占位符个数(即paramIndex 的size)以及占位符次序(slot:即参数在ParameterMappings中的顺序)
        int index = 0;
        ArrayList<Integer> paramIndex = new ArrayList<>();
        while(matcher.find(index)){
            index = matcher.end();
            String sqlPart = sql.substring(0, index);
            int slot = index - sqlPart.replace("?", "").length() + paramIndex.size() ;
            paramIndex.add(slot);
            paramIndex.add(slot + 1);
        }
        //替换子查询
        String companyPeriodSql = matcher.replaceAll(REPLACE_TXT);
        cacheKey = args.length == 4 ? executor.createCacheKey(ms, parameter, rowBounds, boundSql) : (CacheKey) args[4];
        //处理参数
        Object parameterObject = processParameterObject(ms, parameter, boundSql, cacheKey, paramIndex);
        BoundSql companyPeriodBoundSql = new BoundSql(ms.getConfiguration(), companyPeriodSql, boundSql.getParameterMappings(), parameterObject);
        Map<String, Object> additionalParameters = ExecutorUtil.getAdditionalParameter(boundSql);
        //设置动态参数
        for (String key : additionalParameters.keySet()) {
            companyPeriodBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
        }
        return executor.query(ms, parameterObject, RowBounds.DEFAULT, resultHandler, cacheKey, companyPeriodBoundSql);
    }
    public Object processParameterObject(MappedStatement ms, Object parameterObject, BoundSql boundSql, CacheKey pageKey, ArrayList<Integer> paramIndex) {
        //处理参数
        Map<String, Object> paramMap = null;
        if (parameterObject == null) {
            paramMap = new HashMap<>();
        } else if (parameterObject instanceof Map) {
            //解决不可变Map的情况
            paramMap = new HashMap<>();
            paramMap.putAll((Map) parameterObject);
        } else {
            paramMap = new HashMap<>();
            // sqlSource为ProviderSqlSource时,处理只有1个参数的情况
            if (ms.getSqlSource() instanceof ProviderSqlSource) {
                String[] providerMethodArgumentNames = ExecutorUtil.getProviderMethodArgumentNames((ProviderSqlSource) ms.getSqlSource());
                if (providerMethodArgumentNames != null && providerMethodArgumentNames.length == 1) {
                    paramMap.put(providerMethodArgumentNames[0], parameterObject);
                    paramMap.put("param1", parameterObject);
                }
            }
            //动态sql时的判断条件不会出现在ParameterMapping中,但是必须有,所以这里需要收集所有的getter属性
            //TypeHandlerReGIStry可以直接处理的会作为一个直接使用的对象进行处理
            boolean hasTypeHandler = ms.getConfiguration().getTypeHandlerRegistry().hasTypeHandler(parameterObject.getClass());
            MetaObject metaObject = MetaObjectUtil.forObject(parameterObject);
            //需要针对注解形式的MyProviderSqlSource保存原值
            if (!hasTypeHandler) {
                for (String name : metaObject.getGetterNames()) {
                    paramMap.put(name, metaObject.getValue(name));
                }
            }
            //下面这段方法,主要解决一个常见类型的参数时的问题
            if (boundSql.getParameterMappings() != null && boundSql.getParameterMappings().size() > 0) {
                for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) {
                    String name = parameterMapping.getProperty();
                    if (!name.equals(GLOBALPERIOD)
                            && paramMap.get(name) == null) {
                        if (hasTypeHandler
                                || parameterMapping.getJavaType().equals(parameterObject.getClass())) {
                            paramMap.put(name, parameterObject);
                            break;
                        }
                    }
                }
            }
        }
        return processPageParameter(ms, paramMap, boundSql, pageKey, paramIndex);
    }
    private final static String GLOBALPERIOD = "globalPeriod";
    public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, BoundSql boundSql, CacheKey pageKey, ArrayList<Integer> paramIndex) {
        paramMap.put(GLOBALPERIOD, getPeriod());
        //处理pageKey
        pageKey.update(getPeriod());
        //处理参数配置
        handleParameter(boundSql, ms, paramIndex);
        return paramMap;
    }
    protected void handleParameter(BoundSql boundSql, MappedStatement ms,  ArrayList<Integer> paramIndex) {
        if (boundSql.getParameterMappings() != null) {
            List<ParameterMapping> newParameterMappings = new ArrayList<>(boundSql.getParameterMappings());
            for (Integer index : paramIndex) {
                if(index < newParameterMappings.size()) {
                    newParameterMappings.add(index, new ParameterMapping.Builder(ms.getConfiguration(), GLOBALPERIOD, String.class).build());
                }else{
                    newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), GLOBALPERIOD, String.class).build());
                }
            }
            MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
            metaObject.setValue("parameterMappings", newParameterMappings);
        }
    }
    private final static String Q = "Q";
    private final static String H = "H";
    private String getPeriod(){
        //使用threadlocal保存从request中获取的参数,此处不再描述
        String period = PeriodHolder.getPeriod();
        if(NumberUtil.isNumber(period)){
            return period;
        }else if(period.contains(Q)){
            return period.substring(0, 4) + Integer.parseInt(period.substring(5)) * 3;
        }else if(period.contains(H)){
            return period.substring(0, 4) + Integer.parseInt(period.substring(5)) * 6;
        }else{
            throw new ServiceException("非法期间:" + period);
        }
    }
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
    @Override
    public void setProperties(Properties properties) {
        //nothing to do...
    }
}

2、AutoConfiguration代码实现


package org.cnbi.project.autoconfig;
import com.GitHub.pagehelper.autoconfigure.PageHelperAutoConfiguration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.cnbi.project.other.sql.intercept.ParamInterceptor;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.Iterator;
import java.util.List;

@AutoConfigureAfter({MybatisAutoConfiguration.class, PageHelperAutoConfiguration.class})
@Configuration
public class ParamIntecepterAutoConfiguration {
    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;
    public ParamIntecepterAutoConfiguration() {
    }
    @PostConstruct
    public void addParamInterceptor() {
        ParamInterceptor interceptor = new ParamInterceptor();
        Iterator var3 = this.sqlSessionFactoryList.iterator();
        while(var3.hasNext()) {
            SqlSessionFactory sqlSessionFactory = (SqlSessionFactory)var3.next();
            sqlSessionFactory.getConfiguration().addInterceptor(interceptor);
        }
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: Mybatis框架中Interceptor接口的使用说明

本文链接: https://lsjlt.com/news/136460.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作