mybatis Interceptor对UpdateTime自动处理的实现方法
前言
一般数据库的表结构都会有update_time,修改时间,因为这个字段基本与业务没有太大关联,因此开发过程中经常会忘记设置这两个字段的值,本插件就是来解决这个问题。同样的想生成id,create_time等操作都是可以以同样的方式解决。想折腾的同学还可以通过这中方式自己写个分页插件。
闲话少说上代码。
1.先写一个自定义注解标注是update_time
packagecom.zb.iscrm.annotation;
importjava.lang.annotation.ElementType;
importjava.lang.annotation.Retention;
importjava.lang.annotation.RetentionPolicy;
importjava.lang.annotation.Target;
/**
*@Auther:杨红星
*@Date:2018/11/2809:38
*@Description:
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public@interfaceUpdateTime{
Stringvalue()default"";
}
2.写一个mybatis插件
使用@Intercepts标注这是个mybatis插件,@Signature标注要拦截的操作
packagecom.zb.iscrm.mybatisInterceptor;
importcom.zb.iscrm.annotation.UpdateTime;
importcom.zb.iscrm.utils.DateUtils;
importlombok.extern.slf4j.Slf4j;
importorg.apache.ibatis.executor.Executor;
importorg.apache.ibatis.mapping.MappedStatement;
importorg.apache.ibatis.mapping.SqlCommandType;
importorg.apache.ibatis.plugin.*;
importjava.lang.reflect.Field;
importjava.util.Properties;
/**
*@Auther:杨红星
*@Date:2018/11/2809:41
*@Description:mybatis插件用于执行Update时将当前时间加入
*/
@Slf4j
@Intercepts({@Signature(type=Executor.class,method="update",args={MappedStatement.class,Object.class})})
publicclassUpdateTimeInterceptorimplementsInterceptor{
@Override
publicObjectintercept(Invocationinvocation)throwsThrowable{
MappedStatementmappedStatement=(MappedStatement)invocation.getArgs()[0];
//获取SQL命令
SqlCommandTypesqlCommandType=mappedStatement.getSqlCommandType();
//获取参数
Objectparameter=invocation.getArgs()[1];
if(parameter!=null){
//获取成员变量
Field[]declaredFields=parameter.getClass().getDeclaredFields();
for(Fieldfield:declaredFields){
if(field.getAnnotation(UpdateTime.class)!=null){//update语句插入updateTime
if(SqlCommandType.INSERT.equals(sqlCommandType)||SqlCommandType.UPDATE.equals(sqlCommandType)){
field.setAccessible(true);
if(field.get(parameter)==null){
field.set(parameter,DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));
}
}
}
}
}
//同样的方式也可以在这里添加create_time或者是id的生成等处理
returninvocation.proceed();
}
@Override
publicObjectplugin(Objecttarget){
returnPlugin.wrap(target,this);
}
@Override
publicvoidsetProperties(Propertiesproperties){
}
}
最后在mybatis的配置文件中注册插件,然后就大功告成
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。