说明
项目中需要用到响应时替换某些字段的某些值。文章来源地址https://www.toymoban.com/news/detail-755949.html
代码
package xxx.xxx.xx;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
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.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
/**
* 属性值替换
*
* @author behappyto.cn
*/
@Slf4j
@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 PropertyInterceptor implements Interceptor {
/**
* 当前的值可以放到配置文件、配置中心或者其他方式动态获取
*/
private final static HashMap<String, String> TABLE_COLUMN = new HashMap<>();
static {
TABLE_COLUMN.put("实体类名", "属性名");
}
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object obj = invocation.proceed();
try {
if (ObjectUtils.allNull(obj)) {
return obj;
}
if (!(obj instanceof List)) {
return obj;
}
List<Object> objectList = (List<Object>) obj;
String newValue = "替换的值"
if (StringUtils.isBlank(newValue)) {
return objectList;
}
List<Object> respList = new ArrayList<>();
for (Object object : objectList) {
respList.add(this.getObject(newValue, object));
}
return respList;
} catch (Exception exception) {
log.error("ex", exception);
return obj;
}
}
/**
* 转换对象
*
* @param domain 需要替换的域名
* @param object 数据库的对象
* @return 返回 转换后的对象信息
* @throws IllegalAccessException 异常
*/
private Object getObject(String domain, Object object) throws IllegalAccessException {
Class<?> aClass = object.getClass();
String tableEntry = aClass.getSimpleName();
String columnField = TABLE_COLUMN.get(tableEntry);
if (StringUtils.isNotBlank(columnField)) {
Field[] fields = ReflectUtil.getFields(aClass);
Optional<Field> optional = Arrays.stream(fields).filter(item ->
item.getName().equals(columnField)).findFirst();
if (!optional.isPresent()) {
return object;
}
Field field = optional.get();
Object obj = field.get(tableEntry);
if (obj instanceof String) {
field.set(field.getName(), MessageFormat.format((String) obj, domain));
}
}
return object;
}
}
文章来源:https://www.toymoban.com/news/detail-755949.html
到了这里,关于【MyBatis】拦截查询结果同时动态替换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!