剛學習
Mybatis
攔截器方面,在網上找了不少關於Mybatis
攔截器方面的文章,本身也嘗試過寫過幾個,可是關於結果集的攔截始終沒有找到合適的(PS: 不要噴我,畢竟是新手)。也在segmentfault 上提問過,依然沒有找到一個易於理解的,後來本身慢慢理解了之後,本身寫了個入門的,做爲本身的回答。java
用Mybatis
實現過以下需求sql
查詢用戶基本信息表,查詢結果返回是
List<Map<String,Object>>
的結果集,對其中的某個字段進行加密apache
CREATE TABLE usr_basic_inf( USR_ID VARCHAR(20) NOT NULL COMMENT '用戶ID,01+18位互斥隨機數' , USR_REAL_NME VARCHAR(50) NOT NULL COMMENT '用戶真實姓名' , CERT_TYPE VARCHAR(4) COMMENT '證件種類' , CERT_NO VARCHAR(100) COMMENT '證件號碼' , RES_FLD VARCHAR(300) COMMENT '預留字段 ' , PRIMARY KEY(USR_ID) ) COMMENT='用戶基礎信息表';
USR_ID | USR_REAL_NME | CERT_TYPE | CERT_NO | RES_FLD |
---|---|---|---|---|
01000000000000000001 | 張三 | 0101 | 101222010199913291 | (NULL) |
使用Mybatis
對Executor.class
的'qurey'
方法進行攔截,並對返回結果集進行處理segmentfault
package com.ceabox.interceptor; import java.util.ArrayList; import java.util.Map; import java.util.Properties; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.MappedStatement; 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.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; @Intercepts({ @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) }) public class InterceptorForQry implements Interceptor { @SuppressWarnings({ "rawtypes", "unchecked" }) public Object intercept(Invocation invocation) throws Throwable { Object result = invocation.proceed(); //執行請求方法,並將所得結果保存到result中 if (result instanceof ArrayList) { ArrayList resultList = (ArrayList) result; for (int i = 0; i < resultList.size(); i++) { if (resultList.get(i) instanceof Map) { Map resultMap = (Map) resultList.get(i); resultMap.put("CERT_NO", "這個是加密結果"); //取出相應的字段進行加密 } } } return result; } public Object plugin(Object target) { System.out.println("this is the proceed ===>>" + target); return Plugin.wrap(target, this); } public void setProperties(Properties arg0) { System.out.println("this is the properties ===>>" + arg0); } }
在mybatis配置文件中註冊插件:session
<plugins> <plugin interceptor="com.ceabox.interceptor.InterceptorForQry"></plugin> </plugins>
{ USR_ID=01000000000000000001, RES_FLD=null, CERT_NO=這個是加密結果, CERT_TYPE=0101, USR_REAL_NME=張三 }