好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Mybatis Interceptor 拦截器的实现

mybatis采用责任链模式,通过动态代理组织多个拦截器(插件),通过这些拦截器可以改变mybatis的默认行为(诸如sql重写之类的),由于插件会深入到mybatis的核心,因此在编写自己的插件前最好了解下它的原理,以便写出安全高效的插件。

拦截器(interceptor)在 mybatis 中被当做插件(plugin)对待,官方文档提供了 executor,parameterhandler,resultsethandler,statementhandler 共4种,并且提示[这些类中方法的细节可以通过查看每个方法的签名来发现,或者直接查看 mybatis 发行包中的源代码]。

拦截器的使用场景主要是更新数据库的通用字段,分库分表,加解密等的处理。

1. interceptor

拦截器均需要实现该 org.apache.ibatis.plugin.interceptor 接口。

2. intercepts 拦截器

?

1

2

3

@intercepts ({

     @signature (type = executor. class , method = "update" , args = {mappedstatement. class , object. class })

})

拦截器的使用需要查看每一个type所提供的方法参数。

signature 对应 invocation 构造器,type 为 invocation.object,method 为 invocation.method,args 为 invocation.object[]。

method 对应的 update 包括了最常用的 insert/update/delete 三种操作,因此 update 本身无法直接判断sql为何种执行过程。

args 包含了其余所有的操作信息, 按数组进行存储, 不同的拦截方式有不同的参数顺序, 具体看type接口的方法签名, 然后根据签名解析。

3. object 对象类型

args 参数列表中,object.class 是特殊的对象类型。如果有数据库统一的实体 entity 类,即包含表公共字段,比如创建、更新操作对象和时间的基类等,在编写代码时尽量依据该对象来操作,会简单很多。该对象的判断使用

?

1

2

3

4

object parameter = invocation.getargs()[ 1 ];

if (parameter instanceof baseentity) {

   baseentity entity = (baseentity) parameter;

}

即可,根据语句执行类型选择对应字段的赋值。

如果参数不是实体,而且具体的参数,那么 mybatis 也做了一些处理,比如 @param("name") string name 类型的参数,会被包装成 map 接口的实现来处理,即使是原始的 map 也是如此。使用

?

1

2

3

4

object parameter = invocation.getargs()[ 1 ];

if (parameter instanceof map) {

   map map = (map) parameter;

}

即可,对具体统一的参数进行赋值。

4. sqlcommandtype 命令类型

executor 提供的方法中, update 包含了 新增,修改和删除类型,无法直接区分,需要借助 mappedstatement 类的属性 sqlcommandtype 来进行判断,该类包含了所有的操作类型

?

1

2

3

public enum sqlcommandtype {

  unknown, insert, update, delete, select, flush;

}

毕竟新增和修改的场景,有些参数是有区别的,比如创建时间和更新时间,update 时是无需兼顾创建时间字段的。

?

1

2

mappedstatement ms = (mappedstatement) invocation.getargs()[ 0 ];

sqlcommandtype commandtype = ms.getsqlcommandtype();

5. 实例

自己编写的小项目中,需要统一给数据库字段属性赋值:

?

1

2

3

4

5

6

7

public class baseentity {

   private int id;

   private int creator;

   private int updater;

   private long createtime;

   private long updatetime;

}

dao 操作使用了实体和参数的方式,个人建议还是统一使用实体比较简单,易读。

使用实体:

?

1

int add(bookentity entity);

使用参数:

 

复制代码 代码如下:

int update(@param("id") int id, @param("url") string url, @param("description") string description, @param("playcount") int playcount, @param("creator") int creator, @param("updatetime") long updatetime);

 

完整的例子:

?

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

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

package com.github.zhgxun.talk测试数据mon.plugin;

 

import com.github.zhgxun.talk测试数据mon.util.dateutil;

import com.github.zhgxun.talk测试数据mon.util.userutil;

import com.github.zhgxun.talk.entity.baseentity;

import com.github.zhgxun.talk.entity.userentity;

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.interceptor;

import org.apache.ibatis.plugin.intercepts;

import org.apache.ibatis.plugin.invocation;

import org.apache.ibatis.plugin.plugin;

import org.apache.ibatis.plugin.signature;

import org.springframework.stereotype测试数据ponent;

 

import java.util.map;

import java.util.properties;

 

/**

  * 全局拦截数据库创建和更新

  * <p>

  * signature 对应 invocation 构造器, type 为 invocation.object, method 为 invocation.method, args 为 invocation.object[]

  * method 对应的 update 包括了最常用的 insert/update/delete 三种操作, 因此 update 本身无法直接判断sql为何种执行过程

  * args 包含了其余多有的操作信息, 按数组进行存储, 不同的拦截方式有不同的参数顺序, 具体看type接口的方法签名, 然后根据签名解析, 参见官网

  *

  * @link http://HdhCmsTestmybatis.org/mybatis-3/zh/configuration.html#plugins 插件

  * <p>

  * mappedstatement 包括了sql具体操作类型, 需要通过该类型判断当前sql执行过程

  */

@component

@intercepts ({

     @signature (type = executor. class , method = "update" , args = {mappedstatement. class , object. class })

})

@slf4j

public class normalplugin implements interceptor {

 

   @override

   @suppresswarnings ( "unchecked" )

   public object intercept(invocation invocation) throws throwable {

     // 根据签名指定的args顺序获取具体的实现类

     // 1. 获取mappedstatement实例, 并获取当前sql命令类型

     mappedstatement ms = (mappedstatement) invocation.getargs()[ 0 ];

     sqlcommandtype commandtype = ms.getsqlcommandtype();

 

     // 2. 获取当前正在被操作的类, 有可能是java bean, 也可能是普通的操作对象, 比如普通的参数传递

     // 普通参数, 即是 @param 包装或者原始 map 对象, 普通参数会被 mybatis 包装成 map 对象

     // 即是 org.apache.ibatis.binding.mappermethod$parammap

     object parameter = invocation.getargs()[ 1 ];

     // 获取拦截器指定的方法类型, 通常需要拦截 update

     string methodname = invocation.getmethod().getname();

     log.info( "normalplugin, methodname; {}, commandtype: {}" , methodname, commandtype);

 

     // 3. 获取当前用户信息

     userentity userentity = userutil.getcurrentuser();

     // 默认测试参数值

     int creator = 2 , updater = 3 ;

 

     if (parameter instanceof baseentity) {

       // 4. 实体类

       baseentity entity = (baseentity) parameter;

       if (userentity != null ) {

         creator = entity.getcreator();

         updater = entity.getupdater();

       }

       if (methodname.equals( "update" )) {

         if (commandtype.equals(sqlcommandtype.insert)) {

           entity.setcreator(creator);

           entity.setupdater(updater);

           entity.setcreatetime(dateutil.gettimestamp());

           entity.setupdatetime(dateutil.gettimestamp());

         } else if (commandtype.equals(sqlcommandtype.update)) {

           entity.setupdater(updater);

           entity.setupdatetime(dateutil.gettimestamp());

         }

       }

     } else if (parameter instanceof map) {

       // 5. @param 等包装类

       // 更新时指定某些字段的最新数据值

       if (commandtype.equals(sqlcommandtype.update)) {

         // 遍历参数类型, 检查目标参数值是否存在对象中, 该方式需要应用编写有一些统一的规范

         // 否则均统一为实体对象, 就免去该重复操作

         map map = (map) parameter;

         if (map.containskey( "creator" )) {

           map.put( "creator" , creator);

         }

         if (map.containskey( "updatetime" )) {

           map.put( "updatetime" , dateutil.gettimestamp());

         }

       }

     }

     // 6. 均不是需要被拦截的类型, 不做操作

     return invocation.proceed();

   }

 

   @override

   public object plugin(object target) {

     return plugin.wrap(target, this );

   }

 

   @override

   public void setproperties(properties properties) {

   }

}

6. 感受

其它几种类型,后面在看,尤其是分页。

在编写代码的过程中,有时候还是需要先知道对象的类型,比如 object.class 跟 interface 一样,很多时候仅仅代表一种数据类型,需要明确知道后再进行操作。

@param 标识的参数其实会被 mybatis 封装成 org.apache.ibatis.binding.mappermethod$parammap 类型,一开始我就是使用

?

1

2

3

for (field field:parameter.getclass().getdeclaredfields()) {

 

}

的方式获取,以为这些都是对象的属性,通过反射获取并修改即可,实际上发现对象不存在这些属性,但是打印出的信息中,明确有这些字段的,网上参考一些信息后,才知道这是一个 map 类型,问题才迎刃而解。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://segmentfault测试数据/a/1190000017393523

查看更多关于Mybatis Interceptor 拦截器的实现的详细内容...

  阅读:22次