使用mybatis Interceptor對UpdateTime自動處理
一般資料庫的表結構都會有update_time,修改時間,因為這個欄位基本與業務沒有太大關聯,因此開發過程中經常會忘記設定這兩個欄位的值,本外掛就是來解決這個問題。同樣的想生成id,create_time等操作都是可以以同樣的方式解決。想折騰的同學還可以通過這中方式自己寫個分頁外掛。閒話少說上程式碼。
1. 先寫一個自定義註解標註是update_time
package com.zb.iscrm.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @Auther: 楊紅星 * @Date: 2018/11/28 09:38 * @Description: */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface UpdateTime { String value() default ""; } 複製程式碼
2. 寫一個mybatis外掛
使用@Intercepts標註這是個mybatis外掛,@Signature標註要攔截的操作
package com.zb.iscrm.mybatisInterceptor; import com.zb.iscrm.annotation.UpdateTime; import com.zb.iscrm.utils.DateUtils; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlCommandType; import org.apache.ibatis.plugin.*; import java.lang.reflect.Field; import java.util.Properties; /** * @Auther: 楊紅星 * @Date: 2018/11/28 09:41 * @Description: mybatis外掛 用於執行Update時將當前時間加入 */ @Slf4j @Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) }) public class UpdateTimeInterceptorimplements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; // 獲取 SQL 命令 SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType(); // 獲取引數 Object parameter = invocation.getArgs()[1]; if (parameter != null) { // 獲取成員變數 Field[] declaredFields = parameter.getClass().getDeclaredFields(); for (Field field : 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的生成等處理 return invocation.proceed(); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { } } 複製程式碼
最後在mybatis的配置檔案中註冊外掛,然後就大功告成
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--外掛註冊--> <plugins> <plugin interceptor="com.zb.iscrm.mybatisInterceptor.UpdateTimeInterceptor"/> </plugins> </configuration> 複製程式碼