一般数据库的表结构都会有update_time,修改时间,因为这个字段基本与业务没有太大关联,因此开发过程中经常会忘记设置这两个字段的值,本插件就是来解决这个问题。
先写一个自定义注解标注是update_time 1package com.zb.iscrm.annotation; 2 3import java.lang.annotation.ElementType; 4import java.lang.annotation.Retention; 5import java.lang.annotation.RetentionPolicy; 6import java.lang.annotation.Target; 7@Retention(RetentionPolicy.RUNTIME) 8@Target({ElementType.FIELD}) 9public @interface UpdateTime { 10 String value() default ''; 11}
使用@Intercepts标注这是个mybatis插件,@Signature标注要拦截的操作 1package com.zb.iscrm.mybatisInterceptor; 2 3import com.zb.iscrm.annotation.UpdateTime; 4import com.zb.iscrm.utils.DateUtils; 5import lombok.extern.slf4j.Slf4j; 6import org.apache.ibatis.executor.Executor; 7import org.apache.ibatis.mapping.MappedStatement; 8import org.apache.ibatis.mapping.SqlCommandType; 9import org.apache.ibatis.plugin.*; 10 11import java.lang.reflect.Field; 12import java.util.Properties; 13 14@Slf4j 15@Intercepts({ @Signature(type = Executor.class, method = 'update', args = { MappedStatement.class, Object.class }) }) 16public class UpdateTimeInterceptor implements Interceptor { 17 18 @Override 19 public Object intercept(Invocation invocation) throws Throwable { 20 MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; 21 // 获取 SQL 命令 22 SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType(); 23 // 获取参数 24 Object parameter = invocation.getArgs()[1]; 25 if (parameter != null) { 26 // 获取成员变量 27 Field[] declaredFields = parameter.getClass().getDeclaredFields(); 28 for (Field field : declaredFields) { 29 if (field.getAnnotation(UpdateTime.class) != null) { // update 语句插入 updateTime 30 if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) { 31 field.setAccessible(true); 32 if (field.get(parameter) == null) { 33 field.set(parameter, DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS)); 34 } 35 } 36 } 37 } 38 } 39 //同样的方式也可以在这里添加create_time或者是id的生成等处理 40 41 return invocation.proceed(); 42 } 43 44 @Override 45 public Object plugin(Object target) { 46 return Plugin.wrap(target, this); 47 } 48 49 @Override 50 public void setProperties(Properties properties) { 51 } 52}
1<?xml version='1.0' encoding='UTF-8'?> 2<!DOCTYPE configuration 3 PUBLIC '-////DTD Config 3.0//EN' 4 'http:///dtd/mybatis-3-config.dtd'> 5<configuration> 6 <!--插件注册--> 7 <plugins> 8 <plugin interceptor='com.zb.iscrm.mybatisInterceptor.UpdateTimeInterceptor'/> 9 </plugins> 10</configuration>
同样的想生成id,create_time等操作都是可以以同样的方式解决。想折腾的同学还可以通过这中方式自己写个分页插件... ...
|