使用Mybatis拦截器Interceptor,对查询结果为null时的统一处理

创建拦截器

import cn.hutool.core.util.StrUtil;
import com.anhuihuahong.common.annotation.ResultType;
import com.baomidou.mybatisplus.toolkit.PluginUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.ibatis.executor.resultset.DefaultResultSetHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;

/**
 * @Author: ls.
 * @Date: 2019/4/19 10:15
 */
@Component
@Intercepts({
        @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})
})
public class ResultInterceptor implements Interceptor {
    public static final Logger logger = LoggerFactory.getLogger(ResultInterceptor.class);
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //执行请求方法,并将所得结果保存到result中
        Object result = invocation.proceed();
        if((result instanceof List) && ((List) result).size() == 0){
            DefaultResultSetHandler defaultResultSetHandler = (DefaultResultSetHandler) PluginUtils.realTarget(invocation.getTarget());
            Field mappedStatementField = defaultResultSetHandler.getClass().getDeclaredField("mappedStatement");
            mappedStatementField.setAccessible(true);
            MappedStatement mappedStatement = (MappedStatement) mappedStatementField.get(defaultResultSetHandler);
            String id = (String) mappedStatement.getId();
            //方法所在类的类路径
            String classPath = id.substring(0, id.lastIndexOf("."));
            //执行的方法名称
            String methodName = id.substring(id.lastIndexOf(".") + 1, id.length());
            Class classType = Class.forName(classPath);
            for (Method method : classType.getDeclaredMethods()) {
                if (method.isAnnotationPresent(ResultType.class) && methodName.equals(method.getName())) {
                    String resultType = method.getAnnotation(ResultType.class).value();
                    if(StrUtil.equals("arrayList",resultType)){
                        ((List) result).add(Lists.newArrayList());
                    }else if(StrUtil.equals("hashMap",resultType)){
                        ((List) result).add(Maps.newHashMap());
                    }else if(StrUtil.equals("linkedHashMap",resultType)){
                        ((List) result).add(Maps.newLinkedHashMap());
                    }else if(StrUtil.equals("hashSet",resultType)){
                        ((List) result).add(Sets.newHashSet());
                    }else if(StrUtil.equals("integer",resultType)){
                        ((List) result).add(0);
                    }else if(StrUtil.equals("string",resultType)){
                        ((List) result).add("");
                    }else if(StrUtil.equals("boolean",resultType)){
                        ((List) result).add(false);
                    }else if(StrUtil.equals("entity",resultType)){
                        String genericReturnType = method.getGenericReturnType().getTypeName();
                        ((List) result).add(Class.forName(genericReturnType).newInstance());
                    }
                }
            }
        }
        return result;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}

配置

import com.anhuihuahong.common.interceptor.ResultInterceptor;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: ls.
 * @Date: 2019/4/19 10:15
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /*
     * 拦截结果集
     */
    @Bean
    public ResultInterceptor ResultInterceptor() { return new ResultInterceptor(); }
}

创建注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @Author: ls.
 * @Date: 2019/4/19 16:44
 */

@Target({ElementType.METHOD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ResultType {
    String value();
}

使用

在Dao层中使用

@ResultType("hashMap")
    HashMap getLMobileVariousNum(String unitId);

你可能感兴趣的:(Mybatis,Mybatis,Interceptor)