mybatis intercept

mybatis的拦截器:可以用于SQL执行事件记录,数据变更Log等场景


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;@Overridepublic 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;}@Overridepublic Object plugin(Object target) {//return Plugin.wrap(target,this);}@Overridepublic void setProperties(Properties properties) {this.properties=properties;}
}


查看部分源码:

Plugin 类

public static Object wrap(Object target, Interceptor interceptor) {Map, Set> 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 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);}}




本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部