說明
項(xiàng)目中需要用到響應(yīng)時(shí)替換某些字段的某些值。文章來源地址http://www.zghlxwxcb.cn/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 {
/**
* 當(dāng)前的值可以放到配置文件、配置中心或者其他方式動(dòng)態(tài)獲取
*/
private final static HashMap<String, String> TABLE_COLUMN = new HashMap<>();
static {
TABLE_COLUMN.put("實(shí)體類名", "屬性名");
}
@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;
}
}
/**
* 轉(zhuǎn)換對(duì)象
*
* @param domain 需要替換的域名
* @param object 數(shù)據(jù)庫(kù)的對(duì)象
* @return 返回 轉(zhuǎn)換后的對(duì)象信息
* @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;
}
}
文章來源:http://www.zghlxwxcb.cn/news/detail-755949.html
到了這里,關(guān)于【MyBatis】攔截查詢結(jié)果同時(shí)動(dòng)態(tài)替換的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!