前言
一般數據庫的表結構都會有update_time,修改時間,因為這個字段基本與業務沒有太大關聯,因此開發過程中經常會忘記設置這兩個字段的值,本插件就是來解決這個問題。同樣的想生成id,create_time等操作都是可以以同樣的方式解決。想折騰的同學還可以通過這中方式自己寫個分頁插件。
閑話少說上代碼。
1. 先寫一個自定義注解標注是update_time
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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標注要攔截的操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
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 updatetimeinterceptor implements 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的配置文件中注冊插件,然后就大功告成
1
2
3
4
5
6
7
8
9
10
|
<?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> |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://juejin.im/post/5c036bf4f265da61524d23a3