mybatis拦截器的使用及概念

SqlSession           作为MyBatis工作的主要顶层API,表示和数据库交互的会话,完成必要数据库增删改查功能	(对应下图)			
Executor              MyBatis执行器,是MyBatis 调度的核心,负责SQL语句的生成和查询缓存的维护
StatementHandler   封装了JDBC Statement操作,负责对JDBC statement 的操作,如设置参数、将Statement结果集转换成List集合。
ParameterHandler   负责对用户传递的参数转换成JDBC Statement 所需要的参数,
ResultSetHandler    负责将JDBC返回的ResultSet结果集对象转换成List类型的集合;
TypeHandler          负责java数据类型和jdbc数据类型之间的映射和转换
MappedStatement   MappedStatement维护了一条<select|update|delete|insert>节点的封装, 
SqlSource            负责根据用户传递的parameterObject,动态地生成SQL语句,将信息封装到BoundSql对象中,并返回
BoundSql             表示动态生成的SQL语句以及相应的参数信息
Configuration        MyBatis所有的配置信息都维持在Configuration对象之中。

SqlSession

package com.oppo.interceptor;
import com.mysql.jdbc.Connection;
import com.oppo.pojo.Contract;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.lang.reflect.Field;
import java.sql.Date;
import java.util.*;

@Intercepts({
        @Signature(method = "query", type = Executor.class, args = {
                MappedStatement.class, Object.class, RowBounds.class,
                ResultHandler.class}),
})
public class MybatisIntercetor implements Interceptor {

    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("拦截的对象是:" + invocation.getTarget());
        System.out.println("拦截方法是:" + invocation.getMethod().toString());
        System.out.println("拦截参数是:" + invocation.getArgs().length);

        /*里面封装了执行的方法名如:select,update,insert,delete*/
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object object = invocation.getArgs()[1];
        //注解中method的值
        String methodName = invocation.getMethod().getName();
        //sql类型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();


        Date currentDate = new Date(System.currentTimeMillis());
        //对有要求的字段填值


        Contract contract = null;

        try {
              /*重写过滤方法*/

            contract=(Contract)object;
            contract.setContractTempNumber("190528000195");
            //BoundSql对象中封装了sql,以及参数
            BoundSql boundSql = mappedStatement.getBoundSql(object);
            String sql = boundSql.getSql() + " limit 0,1";      /*拼接sql*/
            List<ParameterMapping> Parame = boundSql.getParameterMappings();    /*ParameterMapping中可以修改参数类型*/
            System.out.print(Parame.get(0).getJdbcType());

            invocation.getArgs()[0] = copyFromNewSql(mappedStatement,boundSql,sql, new ArrayList(boundSql.getParameterMappings()), object);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return invocation.proceed();
    }

    private MappedStatement copyFromNewSql(MappedStatement ms, BoundSql boundSql,
                                           String sql, List<ParameterMapping> parameterMappings, Object parameter) {
        BoundSql newBoundSql = copyFromBoundSql(ms, boundSql, sql, parameterMappings, parameter);
        SqlSource sqlSource = new BoundSqlSqlSource(newBoundSql);
        return copyFromMappedStatement(ms, sqlSource);
    }
    public Object plugin(Object var1) {
        System.out.println("插件方法1--将要包装的目标对象1:" + var1);
        return Plugin.wrap(var1, this);
    }

    public void setProperties(Properties var1) {
        System.out.print("==c==");
        /*获取配置*/
    }

    private BoundSql copyFromBoundSql(MappedStatement ms, BoundSql boundSql,
                                      String sql, List<ParameterMapping> parameterMappings, Object parameter) {
        BoundSql newBoundSql = new BoundSql(ms.getConfiguration(),sql, parameterMappings, parameter);
        for (ParameterMapping mapping : boundSql.getParameterMappings()) {
            String prop = mapping.getProperty();
            if (boundSql.hasAdditionalParameter(prop)) {
                newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
            }
        }
        return newBoundSql;
    }

    //see: MapperBuilderAssistant
    private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(),ms.getId(),newSqlSource,ms.getSqlCommandType());

        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if(ms.getKeyProperties() != null && ms.getKeyProperties().length !=0){
            StringBuffer keyProperties = new StringBuffer();
            for(String keyProperty : ms.getKeyProperties()){
                keyProperties.append(keyProperty).append(",");
            }
            keyProperties.delete(keyProperties.length()-1, keyProperties.length());
            builder.keyProperty(keyProperties.toString());
        }

        //setStatementTimeout()
        builder.timeout(ms.getTimeout());

        //setStatementResultMap()
        builder.parameterMap(ms.getParameterMap());

        //setStatementResultMap()
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());

        //setStatementCache()
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());

        return builder.build();
    }

    public static class BoundSqlSqlSource implements SqlSource {
        private BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }


        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }
}

推荐一个:https://blog.csdn.net/wwe4023/article/details/80557172

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis拦截器MyBatis框架提供的一种机制,用于在执行SQL语句前后进行拦截和处理。通过使用拦截器,我们可以在不修改原有代码的情况下,对SQL语句进行自定义的处理和增强。 使用MyBatis拦截器,需要实现`Interceptor`接口,并且重写`intercept()`方法和`plugin()`方法。`intercept()`方法用于自定义SQL语句的处理逻辑,`plugin()`方法用于生成代理对象。 下面是一个示例,展示如何使用MyBatis拦截器: 首先,创建一个类实现`Interceptor`接口: ```java public class MyInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { // 在执行SQL语句前的逻辑处理 System.out.println("Before executing SQL"); // 执行原始方法 Object result = invocation.proceed(); // 在执行SQL语句后的逻辑处理 System.out.println("After executing SQL"); return result; } @Override public Object plugin(Object target) { // 生成代理对象 return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { // 设置拦截器属性 } } ``` 然后,在配置文件中配置拦截器: ```xml <!-- 配置拦截器 --> <plugins> <plugin interceptor="com.example.MyInterceptor" /> </plugins> ``` 以上示例中,`MyInterceptor`类实现了`intercept()`方法,在其中可以编写自定义的SQL处理逻辑。`plugin()`方法生成了拦截器的代理对象。配置文件中的`<plugins>`标签用于配置拦截器

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值