项目中使用mybatisplus,但是有时候需要用拦截器做一些特殊的处理,主要有以下两种:
1.可以对SQL进行替换
项目中基本所有的查询语句都需要传入no和startTime字段,这两个值对于每次业务来说是全局确定的,一般会放在ThreadLocal中,所以会导致所有的dao接口中都需要增加这两个参数。
xml
<select id="getUserLoginList" resultMap="UserLogin">
select distinct user_id, dom_id
from `user_behavior_analysis`
where `no`=#{no}
and <![CDATA[time >= #{startTime}]]>
and isNotNull(dom_id);
</select>
<select id="getPageVisitList" resultMap="PageVisit">
select distinct resource_id as pg_id, dom_id
from `user_behavior_analysis`
where `no`=#{no}
and op_name = '获取页面数据'
and <![CDATA[time >= #{start_time}]]>
and isNotNull(dom_id);
</select>
....
dao
List<User> getUserLoginList(@Param("no")String no,@Param("startTime")String startTime);
List<Page> getPageVisitList(@Param("no")String no,@Param("startTime")String startTime);
这种方式的缺点:dao层接口中都需要加上这两个参数,并且代码中所有的查询处都需要传入这两个参数,多少会有点冗余。有一种比较好的方式是拦截到这个SQL,然后将这个SQL中这两个参数的值替换掉上下文的值,所以需要使用mybatisplus的拦截器来实现。为了更好地识别出这两个参数,可以通过固定字符占位,例如$PADDING,那么xml就变成了:
xml
<select id="getUserLoginList" resultMap="UserLogin">
select distinct user_id, dom_id
from `user_behavior_analysis`
where `no`=$PADDING(no)
and <![CDATA[time >= $PADDING(startTime)]]>
and isNotNull(dom_id);
</select>
<select id="getPageVisitList" resultMap="PageVisit">
select distinct resource_id as pg_id, dom_id
from `user_behavior_analysis`
where `no`=$PADDING(no)
and op_name = '获取页面数据'
and <![CDATA[time >= $PADDING(start_time)]]>
and isNotNull(dom_id);
</select>
....
dao
List<User> getUserLoginList();
List<Page> getPageVisitList();
2.打印SQL语句的执行时间
通过在执行SQL语句执行前保存一个时间,将执行结束后的时间-执行前的时间就是SQL的执行时间,也可以通过在拦截器中进行处理。
代码 如下:
@Intercepts({
@Signature(
type = StatementHandler.class,
method = "prepare",
args = { Connection.class, Integer.class }
),
@Signature(type = StatementHandler.class, method = "query",
args = {Statement.class, ResultHandler.class})
})
public class TableShardInterceptor implements Interceptor {
private static final ReflectorFactory defaultReflectorFactory = new DefaultReflectorFactory();
private static final Logger logger = LoggerFactory.getLogger("SQL_LOGGER");
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
MetaObject metaObject = MetaObject.forObject(statementHandler,
SystemMetaObject.DEFAULT_OBJECT_FACTORY,
SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,
defaultReflectorFactory
);
MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
String namespace = mappedStatement.getId();
String className = namespace.substring(0, namespace.lastIndexOf('.'));
Class<?> clazz = Class.forName(className);
String methodType = invocation.getMethod().getName();
if (methodType.equals("prepare")) {
// 获取TableShard注解
TableShard tableShard = clazz.getAnnotation(TableShard.class);
String sql = (String)metaObject.getValue("delegate.boundSql.sql");
if ( tableShard != null ) {
TableNameEnum[] tableNames = tableShard.tableNames();
// 获取源sql
sql = getReplacedSql(sql, tableNames);
// 用新sql代替旧sql, 完成所谓的sql rewrite
metaObject.setValue("delegate.boundSql.sql", sql);
}
return invocation.proceed();
}
if (!methodType.equals("query")) {
return invocation.proceed();
}
// 传递给下一个拦截器处理
long startTime = System.currentTimeMillis();
Object ret = invocation.proceed();
String sql = statementHandler.getBoundSql().getSql().replaceAll("\r\n|\n|\\s+"," ");
logger.info("SQL:【{}】,耗时|{}|ms",sql, System.currentTimeMillis()-startTime);
return ret;
}
@Override
public Object plugin(Object target) {
// 当目标类是StatementHandler类型时,才包装目标类,否者直接返回目标本身, 减少目标被代理的次数
if (target instanceof StatementHandler) {
return Plugin.wrap(target, this);
} else {
return target;
}
}
@Override
public void setProperties(Properties properties) {
}
private String getReplaceSpecialSql(String sql) {
// start_time
sql = sql.replaceAll("\\$PADDING\\(startTime\\)","'"+TableChangedLocal.getStartTimeLocal()+"'");
// no
sql = sql.replaceAll("\\$PADDING\\(no\\)", String.valueOf(TableChangedLocal.getCustomerNo()));
return sql;
}
}
注:TableChangedLocal是Threadlocal上下文信息,线程内都可以访问