mybatis拦截器对UpdateTime自动处理的实现方法

  

  

一般数据库的表结构都会有update_time,修改时间,因为这个字段基本与业务没有太大关联,因此开发过程中经常会忘记设置这两个字段的值,本插件就是来解决这个问题。同样的想生成id, create_time等操作都是可以以同样的方式解决。想折腾的同学还可以通过这中方式自己写个分页插件。

  

闲话少说上代码。

  

<强> 1。先写一个自定义注解标注是update_time
  

        包com.zb.iscrm.annotation;      进口java.lang.annotation.ElementType;   进口java.lang.annotation.Retention;   进口java.lang.annotation.RetentionPolicy;   进口java.lang.annotation.Target;/* *   * @Auther:杨红星   * @Date: 2018/11/28 09:38   * @Description:   */@Retention (RetentionPolicy.RUNTIME)   @Target ({ElementType.FIELD})   公共@ interface UpdateTime {   字符串值()默认””;   }      

<强> 2。写一个mybatis插件
  

  

使用@Intercepts标注这是个mybatis插件,@Signature标注要拦截的操作

        包com.zb.iscrm.mybatisInterceptor;      进口com.zb.iscrm.annotation.UpdateTime;   进口com.zb.iscrm.utils.DateUtils;   进口lombok.extern.slf4j.Slf4j;   进口org.apache.ibatis.executor.Executor;   进口org.apache.ibatis.mapping.MappedStatement;   进口org.apache.ibatis.mapping.SqlCommandType;   进口org.apache.ibatis.plugin。*;      进口java.lang.reflect.Field;   进口java.util.Properties;/* *   * @Auther:杨红星   * @Date: 2018/11/28 09:41   * @Description: mybatis插件用于执行更新时将当前时间加入   */@Slf4j   @Intercepts ({@Signature(类型=执行人。类,方法="更新",arg游戏={MappedStatement。类,对象。类})})   公共类UpdateTimeInterceptor实现拦截器{      @Override   公共对象拦截(调用调用)抛出Throwable {   MappedStatement MappedStatement=(MappedStatement) invocation.getArgs () [0];//获取SQL命令   SqlCommandType SqlCommandType=mappedStatement.getSqlCommandType ();//获取参数   对象参数=invocation.getArgs () [1];   如果(参数!=null) {//获取成员变量   .getDeclaredFields领域[]declaredFields=parameter.getClass () ();   字段(字段:declaredFields) {   如果(field.getAnnotation (UpdateTime.class) !=null){//更新语句插入updateTime   如果(SqlCommandType.INSERT.equals (sqlCommandType) | | SqlCommandType.UPDATE.equals (sqlCommandType)) {   field.setAccessible(真正的);   如果(field.get(参数)==null) {   字段。(参数设置,DateUtils.dateTimeNow (DateUtils.YYYY_MM_DD_HH_MM_SS));   }   }   }   }   }//同样的方式也可以在这里添加create_time或者是id的生成等处理      返回invocation.proceed ();   }      @Override   公共插件对象(对象目标){   返回插件。包装(目标,这个);   }      @Override   公共空间找(属性属性){   }   }      

最后在mybatis的配置文件中注册插件,然后就大功告成
  

        & lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比;   & lt; !DOCTYPE配置   公众”——//mybatis.org//DTD配置3.0//EN”   “http://mybatis.org/dtd/mybatis-3-config.dtd”在   & lt; configuration>   & lt; !——插件注册——比;   & lt; plugins>   & lt;插件拦截=" com.zb.iscrm.mybatisInterceptor.UpdateTimeInterceptor "/比;   & lt;/plugins>   & lt;/configuration>      

  

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。
  

mybatis拦截器对UpdateTime自动处理的实现方法