MybatisPlus查询条件和排序高级封装

1、查询注解



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

@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Query {

    /**
     * 是否进行相等查询
     */
    boolean eq() default true;

    /**
     * 是否模糊查询
     */
    boolean like() default false;

    /**
     * 是否使用in表达式
     */
    boolean in() default false;

    /**
     * 使用in表达式字符串划分符号
     */
    String symbol() default QueryConstant.COMMA;

    /**
     * 是否需要排序
     */
    boolean orderBy() default false;

    /**
     *排序方式,默认升序
     */
    String sortWay() default QueryConstant.ASC;


}

2、查询常量



public class QueryConstant {

    /**
     * 升序
     */
    public static final String ASC="ASC";

    /**
     * 逆序
     */
    public static final String DESC="DESC";

    /**
     * 逗号
     */
    public static final String COMMA=",";

}

3、扩展函数式接口


@FunctionalInterface
public interface ComplexFunction {
    R apply(T t, U u, P p);
}

4、BaseServiceImpl封装

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.regex.Matcher;


@SuppressWarnings({"unused", "unchecked"})
public abstract class BaseServiceImpl, ENTITY extends BaseEntity> extends ServiceImpl implements BaseService {


    @Override
    public boolean updateById(ENTITY entity){
        entity.setDateUpdated(null);
        return SqlHelper.retBool(getBaseMapper().updateById(entity));
    }

    protected  LambdaQueryWrapper buildWrapper(T t) {
        QueryWrapper query = new QueryWrapper<>();
        Field[] fields = t.getClass().getDeclaredFields();
        //构建普通查询条件
        query=buildQueryWrapper(t,query, this::buildQuery);
        //构建排序查询条件
        query=buildQueryWrapper(t,query,this::buildOrderBy);
        return query.lambda();
    }

    /**
     *通用方法构建queryWrapper
     */
    private  QueryWrapper buildQueryWrapper(T t,QueryWrapper queryWrapper, ComplexFunction,QueryWrapper> function){
        Field[] fields=t.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Object o;
            try {
                o = field.get(t);
            } catch (IllegalAccessException e) {
                log.error("反射获取值异常", e);
                throw new BusinessException("反射获取值异常");
            }
            if (ClassUtil.fieldInClass(field.getName(), getEntityClass())) {
                queryWrapper=function.apply(field,o,queryWrapper);
            }
        }
        return queryWrapper;
    }

    /**
     * 构建查询条件
     */
    private QueryWrapper buildQuery(Field field,Object o,QueryWrapper queryWrapper){
        if(Func.isEmpty(o)){
            return queryWrapper;
        }
        Query query = field.getAnnotation(Query.class);
        if (query == null) {
            return queryWrapper;
        }
        String dbName = xX2x_x(field.getName());
        if (query.like()) {
            queryWrapper.like(dbName, o);
            return queryWrapper;
        }
        if (query.in()) {
            if (o instanceof String) {
                queryWrapper.in(dbName, ListUtil.getListByString((String) o, query.symbol()));
            }
            return queryWrapper;
        }
        if(query.eq()){
            queryWrapper.eq(dbName, o);
        }
        return queryWrapper;
    }

    /**
     * 构建排序条件
     */
    private QueryWrapper buildOrderBy(Field field,Object o,QueryWrapper queryWrapper){
        Query query = field.getAnnotation(Query.class);
        if (query == null) {
            return queryWrapper;
        }
        String dbName = xX2x_x(field.getName());
        if(query.orderBy()){
            if(QueryConstant.ASC.equals(query.sortWay())){
                queryWrapper.orderByAsc(dbName);
            }else if(QueryConstant.DESC.equals(query.sortWay())){
                queryWrapper.orderByDesc(dbName);
            }
        }
        return queryWrapper;
    }


    /**
     * 将驼峰转为下划线
     *
     * @param str 字符串
     * @return java.lang.String
     */
    private String xX2x_x(String str) {
        Matcher matcher = RegexConstant.CAPITAL_LETTER.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }


}

你可能感兴趣的:(java,mybatis,开发语言)