MyBatis自定义拦截器
前言
以下主要实现功能是通过MyBatis的拦截器,对数据库的枚举类进行转义。如:颜色,在数据库表存储为int的1、2、3 等。在页面显示时,需要转为红白蓝时需要关联字典表。这时我们可以通拦截器实现,让他帮我进行数据库查询并转成对应的显示。我们只需要在对应的字段上增加注解就可以了。
一、pandas是什么?
示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。
二、代码实现
1. 自定义Interceptor
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
@Intercepts({@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class TypeCastInterceptor implements Interceptor {
private static final Logger logger = LoggerFactory.getLogger(TypeCastInterceptor.class);
private TypeCastService typeCastService;
public TypeCastInterceptor(TypeCastService typeCastService) {
this.typeCastService = typeCastService;
}
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object proceed = invocation.proceed();
if (proceed instanceof ArrayList) {
List result = new ArrayList();
List list = (ArrayList) proceed;
for (Object o : list) {
result.add(typeCast(o));
}
return result;
} else {
return typeCast(proceed);
}
}
@Override
public Object plugin(Object o) {
return Plugin.wrap(o, this);
}
@Override
public void setProperties(Properties properties) {
}
private Object typeCast(Object cla) {
Field[] fields = cla.getClass().getDeclaredFields();
//TODO 处理对应逻辑(需要根据自己业务处理)
for (Field field : fields) {
TypeCast annotation = field.getAnnotation(TypeCast.class);
if (annotation != null && annotation.fieldName() != null && annotation.tableName() != null) {
field.setAccessible(true);
try {
field.set(cla, "11111Field");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return cla;
}
}
2. 自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TypeCast {
String fieldName() default "";
String tableName() default "";
}
3. 将自定义Interceptor加到链中
@Configuration
@AutoConfigureAfter(PageHelperAutoConfiguration.class)
public class TypeCastAutoConfiguration {
@Autowired
private List<SqlSessionFactory> sqlSessionFactoryList;
@Autowired
private TypeCastService typeCastService;
@PostConstruct
public void addMyInterceptor() {
TypeCastInterceptor e = new TypeCastInterceptor(typeCastService);
for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
sqlSessionFactory.getConfiguration().addInterceptor(e);
}
}
}
配置
在src/resources/META_INF/中创建spring.factories文件,注意这里一定要配置正确,如果创建类出问题,项目无法启。并且也没有报错信息输出。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.*.TypeCastAutoConfiguration