mybatis运⾏时拦截ParameterHandler注⼊参数
在实现多租户系统时,每个租户下的⽤户,⾓⾊,权限,菜单都是独⽴的,每张表⾥都有租户Id字段 (tenantId),每次做数据库操作的时候都需要带上这个字段,很烦。
现在的需求就是在mybatis向sql设置参数时拦截,获取当前登录⽤户的tenantId,若参数的集合中没有 tenantId,将当前登录⽤户的tenantId 放到 sql参数的集合中,
这样就不必在业务代码中关⼼租户信息了。
具体的做法就是拦截ParameterHandler的 setParameters ⽅法, 将 tenantId 添加到要设置到参数中,如果是 insert 操作需要 sql ⽣成钱拦截,将tenantId设置到实体中
代码如下
package com.ipampas.panshi.interceptor;
import org.apachemons.lang.StringUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.utor.Executor;
import org.utor.parameter.ParameterHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ClassUtils;
import java.beans.PropertyDescriptor;
import flect.Field;
import flect.InvocationTargetException;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* User : liulu
* Date : 2017/12/1 11:30
* version $Id: ParamInterceptor.java, v 0.1 Exp $
*/
@Intercepts({
@Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class),
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
@Signature(type = Executor.class, method = "createCacheKey", args = {MappedStatement.class, Object.class, RowBounds.class, BoundSql.class})
}
)
public class ParamInterceptor implements Interceptor {
private static final String PARAM_KEY = "tenantId";
@Override
public Object intercept(Invocation invocation) throws Throwable {
注入// 拦截 Executor 的 update ⽅法⽣成sql前将 tenantId 设置到实体中
if (Target() instanceof Executor && Args().length == 2) {
return invokeUpdate(invocation);
}
// 拦截 Executor 的 createCacheKey ⽅法,pageHelper插件会拦截 query ⽅法,调⽤此⽅法,提前将参数设置到参数集合中
if (Target() instanceof Executor && Args().length == 4) {
return invokeCacheKey(invocation);
}
//拦截 ParameterHandler 的 setParameters ⽅法动态设置参数
if (Target() instanceof ParameterHandler) {
return invokeSetParameter(invocation);
}
return null;
}
private Object invokeCacheKey(Invocation invocation) throws Exception {
Executor executor = (Executor) Target();
MappedStatement ms = (MappedStatement) Args()[0];
if (ms.getSqlCommandType() != SqlCommandType.SELECT) {
return invocation.proceed();
}
Object parameterObject = Args()[1];
RowBounds rowBounds = (RowBounds) Args()[2];
BoundSql boundSql = (BoundSql) Args()[3];
List<String> paramNames = new ArrayList<>();
boolean hasKey = hasParamKey(paramNames, ParameterMappings());
if (!hasKey) {
return invocation.proceed();
}
// 改写参数
parameterObject = processSingle(parameterObject, paramNames);
ateCacheKey(ms, parameterObject, rowBounds, boundSql);
}
private Object invokeUpdate(Invocation invocation) throws Exception {
Executor executor = (Executor) Target();
// 获取第⼀个参数
MappedStatement ms = (MappedStatement) Args()[0];
// ⾮ insert 语句不处理
if (ms.getSqlCommandType() != SqlCommandType.INSERT) {
return invocation.proceed();
}
// mybatis的参数对象
Object paramObj = Args()[1];
if (paramObj == null) {
return invocation.proceed();
}
// 插⼊语句只传⼀个基本类型参数, 不做处理
if (ClassUtils.Class())
|| String.class.Class())
|| Number.class.Class())) {
return invocation.proceed();
}
processParam(paramObj);
return executor.update(ms, paramObj);
}
private Object invokeSetParameter(Invocation invocation) throws Exception {
ParameterHandler parameterHandler = (ParameterHandler) Target();
PreparedStatement ps = (PreparedStatement) Args()[0];
// 反射获取 BoundSql 对象,此对象包含⽣成的sql和sql的参数map映射
Field boundSqlField = Class().getDeclaredField("boundSql");
boundSqlField.setAccessible(true);
BoundSql boundSql = (BoundSql) (parameterHandler);
List<String> paramNames = new ArrayList<>();
// 若参数映射没有包含的key直接返回
boolean hasKey = hasParamKey(paramNames, ParameterMappings());
if (!hasKey) {
return invocation.proceed();
}
// 反射获取参数对像
Field parameterField = Class().getDeclaredField("parameterObject");
parameterField.setAccessible(true);
Object parameterObject = (parameterHandler);
// 改写参数
parameterObject = processSingle(parameterObject, paramNames);
// 改写的参数设置到原parameterHandler对象
parameterField.set(parameterHandler, parameterObject);
parameterHandler.setParameters(ps);
return null;
}
// 判断已⽣成sql参数映射中是否包含tenantId
private boolean hasParamKey(List<String> paramNames, List<ParameterMapping> parameterMappings) { boolean hasKey = false;
for (ParameterMapping parameterMapping : parameterMappings) {
if (StringUtils.Property(), PARAM_KEY)) {
hasKey = true;
} else {
paramNames.Property());
}
}
return hasKey;
}
private Object processSingle(Object paramObj, List<String> paramNames) throws Exception {
Map<String, Object> paramMap = new MapperMethod.ParamMap<>();
if (paramObj == null) {
paramMap.put(PARAM_KEY, 1L);
paramObj = paramMap;
// 单参数将参数转为 map
} else if (ClassUtils.Class())
|| String.class.Class())
|| Number.class.Class())) {
if (paramNames.size() == 1) {
paramMap.put(paramNames.iterator().next(), paramObj);
paramMap.put(PARAM_KEY, 1L);
paramObj = paramMap;
}
} else {
processParam(paramObj);
}
return paramObj;
}
private void processParam(Object parameterObject) throws IllegalAccessException, InvocationTargetException { // 处理参数对象如果是 map 且map的key 中没有 tenantId,添加到参数map中
// 如果参数是bean,反射设置值
if (parameterObject instanceof Map) {
((Map) parameterObject).putIfAbsent(PARAM_KEY, 1L);
} else {
PropertyDescriptor ps = Class(), PARAM_KEY);
if (ps != null && ps.getReadMethod() != null && ps.getWriteMethod() != null) {
Object value = ps.getReadMethod().invoke(parameterObject);
if (value == null) {
}
}
}
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论