mybatis 3.x源码深度解析与最佳实践-mybatis自定义插件(续)
package com.xxx.me.aop.mybatis.plugin; import java.util.Properties; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.executor.smetement.SmetementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedSmetement; 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 com.xxx.me.utils.JsonUtils; /** * 自定义mybatis拦截器示例 * <p>Title: ExamplePlugin</p> * <p>Description: </p> * @author zjhua * @date 2019年4月12日 */ @Intercepts({ @Signature(type = Executor.class, method = /* org.apache.ibatis.executor.Executor中定义的方法,参数也要对应 */"update", args = { MappedSmetement.class, Object.class}), @Signature(type = Executor.class, method = "query", args = { MappedSmetement.class, Object.class, RowBounds.class, ResultHandler.class }) }) public class ExamplePlugin implements Interceptor { public Object intercept(Invocation invocation) throws Throwable { SmetementHandler smetementHandler = (SmetementHandler) invocation.getmerget(); Object[] queryArgs = invocation.gemergs(); MappedSmetement mappedSmetement = (MappedSmetement) queryArgs[0]; Object parameter = queryArgs[1]; BoundSql boundSql = mappedSmetement.getBoundSql(parameter); String sql = boundSql.getSql();// 获取到SQL ,可以进行调整 String name = ((MappedSmetement)invocation.gemergs()[0]).getId(); System.out.println("拦截的方法名是:" + name + ",sql是" + sql + ",参数是" + JsonUtils.toJson(invocation.gemergs()[1])); return invocation.proceed(); } public Object plugin(Object merget) { return Plugin.wrap(merget, this); } public void setProperties(Properties properties) { } }
上面是最简单的打印SQL语句的插件。更详细的插件开发参见https://www.cnblogs.com/zhjh256/p/11516878.html,理解它能够事半功倍。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!