mybatis基于结果集的拦截处理实际使用场景较少,因为拦截了结果集再进行修改替换属于比较单一的场景
package com.dlh.sundoctor.intercepter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dlh.sundoctor.model.entity.HuIndustrialPromotionCloudWarehouse;
import org.apache.ibatis.executor.Executor;
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.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* @author
* @date 2022/3/4 11:18
*/
@Intercepts({
@Signature(type = Executor.class, method = "query",
args = { MappedStatement.class,
Object.class,
RowBounds.class,
ResultHandler.class
})
})
public class MybatisInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
//执行请求方法,并将所得结果保存到result中
Object result = invocation.proceed();
if (result instanceof ArrayList) {
ArrayList resultList = (ArrayList) result;
for (int i = 0; i < resultList.size(); i++) {
if (resultList.get(i) instanceof HuIndustrialPromotionCloudWarehouse) {
HuIndustrialPromotionCloudWarehouse ipcw = (HuIndustrialPromotionCloudWarehouse) resultList.get(i);
JSONObject jsonObject = JSON.parseObject(ipcw.getAtTheFirstCloudFactory());
List<Map<String,Object>> maps = (List<Map<String,Object>>) jsonObject.get("listInfo");
for (Map<String, Object> map : maps) {
String link = (String) map.get("link");
map.put("link",link+"?sign=153100");
}
jsonObject.put("listInfo",maps);
ipcw.setAtTheFirstCloudFactory(JSON.toJSONString(jsonObject));
}
}
}
return result;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
package com.dlh.sundoctor.config;
import com.dlh.sundoctor.intercepter.MybatisInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author
* @date 2022/3/4 14:12
*/
@Configuration
public class MybatisInterceptorConfig {
@Bean
public String myInterceptor(SqlSessionFactory sqlSessionFactory) {
sqlSessionFactory.getConfiguration().addInterceptor(new MybatisInterceptor());
return "interceptor";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<plugins>
<plugin interceptor="com.dlh.sundoctor.intercepter.MybatisInterceptor" />
</plugins>
</configuration>
最后在application.properties配置文件里配置 mybatis的配置文件即可
mybatis.configLocation = classpath:mybatis/mybatis-config.xml
|