mybatis intercept
2015-12-28 17:23
393 查看
mybatis的拦截器:可以用于SQL执行事件记录,数据变更Log等场景
查看部分源码:
Plugin 类
package com.tuniu.pcs.core.intercept; 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 java.lang.reflect.Method; import java.util.Properties; /** * Created by zhangtao4 on 2015/12/28. */ @Intercepts({@Signature(type = Executor.class,method = "update",args = {MappedStatement.class,Object.class})}) public class MybatisIntercept implements Interceptor { private Properties properties; @Override public Object intercept(Invocation invocation) throws Throwable { //Method method=invocation.getMethod(); MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; Object parameter = null; if (invocation.getArgs().length > 1) { parameter = invocation.getArgs()[1]; } String sqlId = mappedStatement.getId(); Object returnValue = null; long start = System.currentTimeMillis(); returnValue = invocation.proceed(); long end = System.currentTimeMillis(); long time = (end - start); return returnValue; } @Override public Object plugin(Object target) { // return Plugin.wrap(target,this); } @Override public void setProperties(Properties properties) { this.properties=properties; } }
查看部分源码:
Plugin 类
public static Object wrap(Object target, Interceptor interceptor) { Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor); Class<?> type = target.getClass(); Class<?>[] interfaces = getAllInterfaces(type, signatureMap); if (interfaces.length > 0) { return Proxy.newProxyInstance( type.getClassLoader(), interfaces, new Plugin(target, interceptor, signatureMap)); } return target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { Set<Method> methods = signatureMap.get(method.getDeclaringClass()); if (methods != null && methods.contains(method)) { return interceptor.intercept(new Invocation(target, method, args)); } return method.invoke(target, args); } catch (Exception e) { throw ExceptionUtil.unwrapThrowable(e); } }
相关文章推荐
- Veeam Backup & Replication试用(二):前期准备,配置备份存储空间和VMware vSphere虚拟化平台
- html5 初试 indexedDB
- 【原】Linux Raid 实验
- Servlet 3.0 新特性详解
- python Slope one
- 终极 Shell - ZSH
- HRBUST2189 并查集入门 节点的连接
- PS-点击选中某一个图层
- lz77算法 例子
- Java集合 Json集合之间的转换
- 图像检索公开数据集
- 高效使用Xcode
- 详解 Android 的 Activity 组件
- struct 结构体的用法简单介绍
- http请求流程
- Veeam Backup & Replication试用(一):安装及配置
- 用cxf集成spring的demo
- 老男孩教育——学习三个月的心得体会
- Web项目导出为war文件,热部署到tomcat运行
- angularjs的过滤器