MyBatis Interceptor
MyBatis的拦截器可以用于在以下对象及方法中拦截修改:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
每一个方法会对应不同的参数列表, 这些需要体现在Intercepts的Signature中
配置
除了实现Interceptor接口以外, 需要在项目中做以下配置
application.yml
增加对应的mybatis-config.xml, 因为现在还不支持在yml中配置plugin
mybatis:
type-aliases-package: com.compayn.proj.commons.api.dto
mapper-locations: classpath:mapper/*.xml
config-location: classpath:mybatis-config.xml
mybatis-config.xml
增加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>
<settings>
<setting name="..." value="true" />
</settings> <plugins>
<!-- The invocation order is bottom up -->
<plugin interceptor="com.company.proj.commons.impl.interceptor.BaseInterceptor" />
</plugins> </configuration>
Interceptor实现
一个简单的拦截器实现, 可以输出执行的sql, 以及执行时间.
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.sql.Statement;
import java.util.Properties; @Intercepts({
@Signature(type = StatementHandler.class, method = "batch", args = { Statement.class}),
@Signature(type = StatementHandler.class, method = "update", args = { Statement.class}),
@Signature(type = StatementHandler.class, method = "query", args = { Statement.class, ResultHandler.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class,Object.class})})
public class BaseInterceptor implements Interceptor {
private static Logger logger = LoggerFactory.getLogger(BaseInterceptor.class); /**
* 用于封装目标对象, 可以返回目标对象本身也可以返回一个它的代理, 这将决定是否会进行拦截
*/
@Override
public Object plugin(Object target) {
if (target instanceof Executor) { // 仅当对象为Executor时, 才使用本插件
return Plugin.wrap(target, this);
} else {
return target;
}
} /**
* 用于配置本插件的相关属性
*/
@Override
public void setProperties(Properties properties) {
// Do nothing
} @Override
public Object intercept(Invocation invocation) throws Throwable {
long start = System.currentTimeMillis(); Object target = invocation.getTarget(); //被代理对象 if (target instanceof Executor) {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
Object parameter = invocation.getArgs()[1];
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
String sql = boundSql.getSql();
logger.info("SQL: {}", sql);
} Object result = invocation.proceed();
long duration = System.currentTimeMillis() - start;
logger.info("Time elapsed: {}ms", duration);
return result;
}
}
代码说明
@Intercepts 注解: 这个地方配置需要拦截的对象方法, 每个方法对应一个Signature, 这个Signature由对象类型, 方法名和参数组成, 方法名和参数可以直接参考这个对象的接口.
Object plugin(Object target)接口: 用于封装目标对象, 可以返回目标对象本身也可以返回一个它的代理, 这将决定是否会进行拦截
void setProperties(Properties properties)接口: 用于配置本插件的相关属性, 值可以通过Mybatis配置文件传入
Object intercept(Invocation invocation) throws Throwable接口: 执行拦截的方法, 其中 invocation.getTarget() 可以看到实际被代理的对象, 根据对象类型不同, 可以读取这个对象方法的参数并进行需要的操作.
MyBatis Interceptor的更多相关文章
- Mybatis Interceptor 拦截器原理 源码分析
Mybatis采用责任链模式,通过动态代理组织多个拦截器(插件),通过这些拦截器可以改变Mybatis的默认行为(诸如SQL重写之类的),由于插件会深入到Mybatis的核心,因此在编写自己的插件前最 ...
- mybatis Interceptor拦截器代码详解
mybatis官方定义:MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis ...
- mybatis interceptor 处理查询参数及查询结果
拦截器:拦截update,query方法,处理查询参数及返回结果. /** * Created by windwant on 2017/1/12. */ @Intercepts({ @Signatur ...
- MyBatis源码分析(2)—— Plugin原理
@(MyBatis)[Plugin] MyBatis源码分析--Plugin原理 Plugin原理 Plugin的实现采用了Java的动态代理,应用了责任链设计模式 InterceptorChain ...
- mybatis 打印sql 语句
拦截器 package com.cares.asis.mybatis.interceptor; import java.text.DateFormat; import java.util.Date; ...
- mybatis 控制台打印sql
开发时调试使用 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBe ...
- 在mybatis执行SQL语句之前进行拦击处理
转载自:http://blog.csdn.net/hfmbook/article/details/41985853 比较适用于在分页时候进行拦截.对分页的SQL语句通过封装处理,处理成不同的分页sql ...
- Mybatis拦截器介绍
拦截器的一个作用就是我们可以拦截某些方法的调用,我们可以选择在这些被拦截的方法执行前后加上某些逻辑,也可以在执行这些被拦截的方法时执行自己的逻辑而不再执行被拦截的方法.Mybatis拦截器设计的一个初 ...
- MyBatis查询两个字段,返回Map,一个字段作为key,一个字段作为value的实现
1. 问题描述 在使用MyBatis,我们经常会遇到这种情况:SELECT两个字段,需要返回一个Map,其中第一个字段作为key,第二个字段作为value.MyBatis的MapKey虽然很实用,但并 ...
- MyBatis浅尝笔记
MyBatis应属于一种轻量级的java持久层技术,它通过简单的SQL xml或注解,将数据库数据映射到接口与POJO.最近项目要用到mybatis,所以学习之后在这里做个总结,文中的示例以xml配置 ...
随机推荐
- 【TouchGFX】实测工程所在路径深度不可超过10级(10级有效)
实测环境 win10 64bit touchgfx designer 4.13.0
- Oracle数据类型的简单学习之一
Oracle数据类型的简单学习之一 背景 因为信创安可替代的发展 有很多项目提到了数据库切换到国产数据库的要求. 一般情况是要求从Oracle/SQLServer 迁移到国产的: 达梦/瀚高/人大金仓 ...
- Oceanbase开源版 数据库恢复MySQL数据库的过程
# Oceanbase开源版 数据库恢复MySQL数据库的过程 背景 想进行一下Oceanbase数据库的兼容性验证. 想着用app create 数据库的方式周期比较长. 所以我想着换一套 备份恢复 ...
- [转帖]【MySQL 8】MySQL 5.7都即将停只维护了,是时候学习一波MySQL 8了!
https://juejin.cn/post/7111255789876019208 MySQL 8新特性 选择MySQL 8的背景:MySQL 5.6已经停止版本更新了,对于 MySQL 5.7 版 ...
- [转帖]将 Cloudflare 连接到互联网的代理——Pingora 的构建方式
https://zhuanlan.zhihu.com/p/575228941 简介 今天,我们很高兴有机会在此介绍 Pingora,这是我们使用 Rust 在内部构建的新 HTTP 代理,它每天处理超 ...
- Redis Cluster in K3S
Redis Cluster in K3S 学习资料 https://www.cnblogs.com/cheyunhua/p/15619317.html https://blog.csdn.net/cq ...
- 【K哥爬虫普法】倒计时21天!事关爬虫er们能否平安回家过年!
我国目前并未出台专门针对网络爬虫技术的法律规范,但在司法实践中,相关判决已屡见不鲜,K 哥特设了"K哥爬虫普法"专栏,本栏目通过对真实案例的分析,旨在提高广大爬虫工程师的法律意识, ...
- 【JS 逆向百例】元素ID定位加密位置,某麻将数据逆向
声明 本文章中所有内容仅供学习交流,抓包内容.敏感网址.数据接口均已做脱敏处理,严禁用于商业用途和非法用途,否则由此产生的一切后果均与作者无关,若有侵权,请联系我立即删除! 逆向目标 目标:某在线麻将 ...
- flask session 伪造
flask session 伪造 一.session的作用 由于http协议是一个无状态的协议,也就是说同一个用户第一次请求和第二次请求是完全没有关系的,但是现在的网站基本上有登录使用的功能,这就要求 ...
- Vue基础系列文章05----babel安装与使用
1.安装babel-node包,运行: 1) npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node 2 ...