Mybatis 拦截器实现

  • mybatis提供了Interceptor接口可以对数据库操作进行拦截。
  • maven 依赖

       org.mybatis
       mybatis
       3.4.5
 

或者添加maven-plugin


      org.mybatis.generator
      mybatis-generator-maven-plugin
      1.3.0
      
            
            true
            
            true
       
 
  • 拦截器启用
    由于项目为springcloud框架,故秩序在拦截器上添加@Component即可
package com.hyx.interceptor;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Properties;


/**
 * create by 嘿小逗比就是你 on 2018/7/6
 */
@Intercepts( {
        @Signature(method = "update", type = Executor.class, args = {
                MappedStatement.class, Object.class})})
@Component
public class MybatisInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //需要进行的操作
        Object[] args = invocation.getArgs();//
        MappedStatement ms = (MappedStatement) args[0];
        Class clazz = args[1].getClass();
        Method[] methods = clazz.getDeclaredMethods();
        if("INSERT".equals(ms.getSqlCommandType().name())){
              for (Method method : methods) {//获取字段名
              methodName = method.getName();
              }
            Method getTime = clazz.getMethod("getTime");//通过字段名获取值
            Object time= getTime.invoke(args[1]);
            Method setTime = clazz.getMethod("setTime", Date.class);
            setTime.invoke(args[1], new Date());// 设置值
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }

}

  • 注意:
    @Signature中常用method有"update","query","prepare",而且对于接口Executor,method只定义了update,query,flushStatements,commit,rollback,createCacheKey,isCached,clearLocalCache,deferLoad,getTransaction,close,isClosed这几个方法,没有delete和insert方法。insert和delete操作均使用"update"。
@Intercepts( {
       @Signature(method = "query", type = Executor.class, args = {
              MappedStatement.class, Object.class, RowBounds.class,
              ResultHandler.class }),
       @Signature(method = "update", type = Executor.class, args = {
                MappedStatement.class, Object.class})
       @Signature(method = "prepare", type = StatementHandler.class, args = { Connection.class }) })

你可能感兴趣的:(Mybatis 拦截器实现)