(六) mybatis 源码之 四大对象与插件开发
程序员文章站
2022-05-04 08:45:21
拦截器 Interceptor在创建四大对象的时候, 都应用到了拦截器/* 以下四个方法都应用了拦截器, 实现 Interceptor 接口为 mybatis 进行拓展 */public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) { ParameterHandler parameterHandler =...
拦截器 Interceptor
在创建四大对象的时候, 都应用到了拦截器
/* 以下四个方法都应用了拦截器, 实现 Interceptor 接口为 mybatis 进行拓展 */
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
return parameterHandler;
}
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
ResultHandler resultHandler, BoundSql boundSql) {
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
// 同时在里面创建了 ParameterHandler , ResultHandler 对象
// 一个 StatementHandler 对象包含了 ParameterHandler , ResultHandler 对象
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
}
else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
}
else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
// 拦截器, 应用插件
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
实现 Interceptor 接口, 并在全局配置文件中加入此插件
<plugins>
<plugin interceptor="com.gp.ibatis.interceptor.MyInterceptor"></plugin>
</plugins>
四大对象
Executor
执行器, 增删改查, 回滚, 提交等操作
ParameterHandler
参数处理器, 为预编译的 SQL 设置参数
StatementHandler
SQL 执行器, 预编译 SQL, 发送 SQL 到数据库中
ResultSetHandler
结果集处理器, 将 SQL 的执行结果与 POJO 进行绑定, 数据库的类型与 Java 类型绑定
其中, ParameterHandler 和 ResultSetHandler 都会用到 TypeHandler, 他们的关系如下 :
插件原理
从上面可以知道, 创建四大对象时, 应用了插件, 其实就是调用 Interceptor 的 plugin 方法
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}
我们自定义一个拦截器
/**
* 完成插件签名, 告诉 mybatis 当前插件来拦截哪个对象的那个方法
* 如果存在多个插件 , mybatis 将会创建多重代理, 一次被拦截
* 拦截顺序按照配置插件的逆序执行
*/
@Intercepts({
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
})
public class MyInterceptor implements Interceptor {
private Integer pageNum;
private Integer pageMaxSize;
// 在目标对象的方法执行前, 拦截它
// Invocation 对象包含了 原生对象, 目标方法, 方法参数值
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
Method method = invocation.getMethod();
Object target = invocation.getTarget();
System.out.println(Arrays.toString(args));
System.out.println(method);
System.out.println(target);
Object proceed = invocation.proceed();
return proceed;
}
// 为 target 创建代理对象, 被 Plugin 拦截
@Override
public Object plugin(Object target) {
// 使用 mybatis 提供的工具类
// 根据 this 的元数据创建代理对象
Object wrap = Plugin.wrap(target, this);
return wrap;
}
// 在注册插件的时候, 拿到 <plugin> 标签中的的 Properties 属性值
@Override
public void setProperties(Properties properties) {
Integer pageNum = (Integer) properties.get("pageNum");
Integer pageMaxSize = (Integer) properties.get("pageMaxSize");
this.pageMaxSize = pageMaxSize;
this.pageNum = pageNum;
}
}
Plugin
public class Plugin implements InvocationHandler {
private final Object target;
private final Interceptor interceptor;
private final Map<Class<?>, Set<Method>> signatureMap;
private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
this.target = target;
this.interceptor = interceptor;
this.signatureMap = signatureMap;
}
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;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// 拿到 Interceptor 的元数据
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
// 匹配, 是否是需要拦截的方法
if (methods != null && methods.contains(method)) {
// 如果是 , 执行拦截器的 intercept 方法
// 将 目标对象, 目标方法, 方法参数封装成一个 Invocation 对象
return interceptor.intercept(new Invocation(target, method, args));
}
return method.invoke(target, args);
}
catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
/**
* 拿到元数据, 保存到 Map 中, 返回出去
* @param interceptor
* @return
*/
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
// 检查是否存在 @Interceptss 注解, 没有直接抛出异常
if (interceptsAnnotation == null) {
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
Signature[] sigs = interceptsAnnotation.value();
Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
for (Signature sig : sigs) {
Set<Method> methods = signatureMap.computeIfAbsent(sig.type(), k -> new HashSet<>());
try {
// 需要拦截的方法
Method method = sig.type().getMethod(sig.method(), sig.args());
methods.add(method);
}
catch (NoSuchMethodException e) {
throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
}
}
return signatureMap;
}
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
Set<Class<?>> interfaces = new HashSet<>();
while (type != null) {
// 先拿到此类型的所有接口
for (Class<?> c : type.getInterfaces()) {
// 如果在所有 @Signature 中 type 含有此类型
if (signatureMap.containsKey(c)) {
interfaces.add(c);
}
}
// 处理此类型的父类
type = type.getSuperclass();
}
return interfaces.toArray(new Class<?>[interfaces.size()]);
}
}
分页插件
使用 github 的开源项目 pagehelper (github项目地址), 可以为 mybatis 实现分页效果, 我们也手写一个分页插件
<plugins>
<plugin interceptor="com.gp.ibatis.interceptor.SecondInterceptor">
<!--要显示条目的起始索引(起始索引从0开始, 默认为0)-->
<property name="pageNum" value="0"/>
<!--要显示条目个数-->
<property name="pageMaxSize" value="5"/>
</plugin>
</plugins>
拦截器
package com.gp.ibatis.interceptor;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.util.Properties;
/**
* @author Gp
* @create 2020/7/29 16:52
*/
@Intercepts({
// 拦截 Executor 的四个参数 query 方法
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class SecondInterceptor implements Interceptor {
private Integer pageNum;
private Integer pageMaxSize;
private static final String LIMIT = " limit ";
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
/**
* 不考虑特殊情况, 查询也不带参数
* @param invocation
* @return
* @throws Throwable
*/
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
RowBounds rowBounds = (RowBounds) args[2];
Executor executor = (Executor) invocation.getTarget();
BoundSql boundSql = ms.getBoundSql(null);
String sql = boundSql.getSql();
sql += LIMIT + pageNum + " , " + pageMaxSize;
BoundSql myBoudSql = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), null);
CacheKey cacheKey = executor.createCacheKey(ms, null, rowBounds, myBoudSql);
return executor.query(ms, null, rowBounds, null, cacheKey, myBoudSql);
}
// 在注册插件的时候, 拿到 <plugin> 标签中的的 Properties 属性值
@Override
public void setProperties(Properties properties) {
String pageNum = properties.getProperty("pageNum");
String pageMaxSize = properties.getProperty("pageMaxSize");
try {
this.pageMaxSize = Integer.parseInt(pageMaxSize);
this.pageNum = Integer.parseInt(pageNum);
}
catch (NumberFormatException e) {
throw new RuntimeException("无效参数, 请将值设置为数字!");
}
}
}
本文地址:https://blog.csdn.net/Gp_2512212842/article/details/107658167
下一篇: 夏季甜品汤有哪些?夏季时甜品不可少