MyBatiesPlus简化使用

Demo

class TUserController{
		User user = new User();
        user.setUserName("lijiajun");
 		QueryWrapper qw = BatisPlusQueryUtil.getQueryWrapper(user, "page", "T1.data_status");
        /*
        //未传递分组信息则获取所有com.ljj.birthdaymanager.utils.ibatis.plus.util的注解
        QueryWrapper qw = BatisPlusQueryUtil.getQueryWrapper(user);
        */

        /*
        //不需要进行逻辑删除校验时,传递isUse:false
        QueryWrapper qw = BatisPlusQueryUtil.getQueryWrapper(user, "list",false);
         */

        /*
        QueryWrapper qw = BatisPlusQueryUtil.getQueryWrapper(user, page);
        */

        //指定逻辑删除校验列为T1.data_status,默认列配置于 logic-delete-column: data_status
        List<User> list = testService.list(qw);
}
@Data
class User{
	@Like(group={"list","getByUserName","page"})
	private String userName;
	
	@Eq(group="list","page")
    @Like(group="likePhone", sourceColumn = "T1.f_phone")
    private String phone;
    
	@Eq(group="login")
    private String password;
}

版本

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>

工具代码

BatisPlusUtilLogic.java

public class BatisPlusUtilLogic {

    /**
     * @description: 携带注解的bean转换为条件构造器
     * @data: 2020/6/11 14:25
     */
    protected static void beanToWrapper(Object object, String group, QueryWrapper queryWrapper){
        Class<?> clz = object.getClass();

        List<Field> fieldList = getFiledsInfo(clz.getName());

        for (Field field : fieldList){

            field.setAccessible(true);
            Annotation[] annotations = field.getAnnotations();
            List<Annotation> annotationList = Arrays.asList(annotations);

            if (annotationList == null || annotationList.isEmpty()) continue;

            Object value = null;
            try {
                value = field.get(object);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            if (value == null) continue;

            if(value instanceof String && "".equals(value)) continue;

            filterField(group, queryWrapper, field, value);
        }
    }

    /**
     * @data: 2020/6/11 14:24
     * @description: 将有效的注解转换为wrapper的条件
     */
    protected static void filterField(String group, QueryWrapper queryWrapper, Field field, Object value) {
        Eq eq = field.getAnnotation(Eq.class);
        Ne ne = field.getAnnotation(Ne.class);
        Gt gt = field.getAnnotation(Gt.class);
        Ge ge = field.getAnnotation(Ge.class);
        Lt lt = field.getAnnotation(Lt.class);
        Le le = field.getAnnotation(Le.class);
        Between between = field.getAnnotation(Between.class);
        NotBetween notBetween = field.getAnnotation(NotBetween.class);
        Like like = field.getAnnotation(Like.class);
        NotLike notLike = field.getAnnotation(NotLike.class);
        LikeLeft likeLeft = field.getAnnotation(LikeLeft.class);
        LikeRight likeRight = field.getAnnotation(LikeRight.class);
        In in = field.getAnnotation(In.class);
        NotIn notIn = field.getAnnotation(NotIn.class);

        if (eq != null && isSameGroup(group, eq.group())) {

            String column = "".equals(eq.sourceColumn()) ?
                    propertyToColumn(field.getName()) : eq.sourceColumn();
            queryWrapper.eq(column, value);

        } else if (ne != null && isSameGroup(group, ne.group())) {

            String column = "".equals(ne.sourceColumn()) ?
                    propertyToColumn(field.getName()) :ne.sourceColumn();
            queryWrapper.ne(column, value);

        } else if (gt != null && isSameGroup(group, gt.group())) {

            String column = "".equals(gt.sourceColumn()) ?
                    propertyToColumn(field.getName()) :gt.sourceColumn();
            queryWrapper.gt(column, value);

        } else if (ge != null && isSameGroup(group, ge.group())) {

            String column = "".equals(ge.sourceColumn()) ?
                    propertyToColumn(field.getName()) :ge.sourceColumn();
            queryWrapper.ge(column, value);

        } else if (lt != null && isSameGroup(group, lt.group())) {

            String column = "".equals(lt.sourceColumn()) ?
                    propertyToColumn(field.getName()) :lt.sourceColumn();
            queryWrapper.lt(column, value);

        } else if (le != null && isSameGroup(group, le.group())) {

            String column = "".equals(le.sourceColumn()) ?
                    propertyToColumn(field.getName()) :le.sourceColumn();
            queryWrapper.le(column, value);

        } else if (between != null && isSameGroup(group, between.group())) {

            String column = "".equals(between.sourceColumn()) ?
                    propertyToColumn(field.getName()) :between.sourceColumn();
            Object objBetween = value;
            List<Object> objectBetweenList = castList(objBetween, Object.class);
            if (objectBetweenList != null)
                queryWrapper.between(column, objectBetweenList.get(0), objectBetweenList.get(1));

        } else if (notBetween != null && isSameGroup(group, notBetween.group())) {

            String column = "".equals(notBetween.sourceColumn()) ?
                    propertyToColumn(field.getName()) :notBetween.sourceColumn();
            Object objBetween = value;
            List<Object> objectBetweenList = castList(objBetween, Object.class);
            if (objectBetweenList != null)
                queryWrapper.notBetween(column, objectBetweenList.get(0), objectBetweenList.get(1));

        } else if (like != null && isSameGroup(group, like.group())) {

            String column = "".equals(like.sourceColumn()) ?
                    propertyToColumn(field.getName()) :like.sourceColumn();
            queryWrapper.like(column, value);

        } else if (notLike != null && isSameGroup(group, notLike.group())) {

            String column = "".equals(notLike.sourceColumn()) ?
                    propertyToColumn(field.getName()) :notLike.sourceColumn();
            queryWrapper.notLike(column, value);

        } else if (likeLeft != null && isSameGroup(group, likeLeft.group())) {

            String column = "".equals(likeLeft.sourceColumn()) ?
                    propertyToColumn(field.getName()) :likeLeft.sourceColumn();
            queryWrapper.likeLeft(column, value);

        } else if (likeRight != null && isSameGroup(group, likeRight.group())) {

            String column = "".equals(likeRight.sourceColumn()) ?
                    propertyToColumn(field.getName()) :likeRight.sourceColumn();
            queryWrapper.likeRight(column, value);

        } else if (in != null && isSameGroup(group, in.group())) {

            String column = "".equals(in.sourceColumn()) ?
                    propertyToColumn(field.getName()) :in.sourceColumn();
            Object obj = value;
            List<Object> objectList = castList(obj, Object.class);
            if (objectList != null)
                queryWrapper.in(column, objectList);

        } else if (notIn != null && isSameGroup(group, notIn.group())) {

            String column = "".equals(notIn.sourceColumn()) ?
                    propertyToColumn(field.getName()) :notIn.sourceColumn();
            Object obj = value;
            List<Object> objectList = castList(obj, Object.class);
            if (objectList != null)
                queryWrapper.notIn(column, objectList);
        }
    }

    /**
     * @description: 判断是否属于该组的数据
     * @data: 2020/6/11 13:58
     */
    protected static boolean isSameGroup(String group, String[] fieldGroups) {
        if (group == null) {
            return true;
        }else if(fieldGroups == null || fieldGroups.length == 0){
            return false;
        }
        List<String> list = Arrays.asList(fieldGroups);
        return list.contains(group);
    }

    /**
     * @data: 2020/6/9 16:44
     * @description: obj to list 容错转换
     *               处理如in一类的多值条件处理
     */
    protected static <T> List<T> castList(Object obj, Class<T> clazz) {
        if (obj == null) return null;

        List<T> result = new ArrayList<T>();
        if(obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                result.add(clazz.cast(o));
            }
        }else if(obj instanceof Arrays){
            for (Object o : (Object[]) obj) {
                result.add(clazz.cast(o));
            }
        }else if(obj instanceof String){
            for (Object o :  ((String) obj).split(",")) {
                result.add(clazz.cast(o));
            }
        }else{
            throw new ClassCastException("Only the following types can be supported: List.class, Object[].class, String.class(Joining together',').");
        }

        return result;
    }

    /**
     * @description: 获取所有属性
     * @data: 2020/6/9 16:18
     */
    protected static List<Field> getFiledsInfo(String className) {
        List<Field> list = new ArrayList<>();
        Class<?> clazz = null;
        try {
            clazz = Class.forName(className);
            Field[] fields = clazz.getDeclaredFields();
            list.addAll(Arrays.asList(fields));
            Class<?> superClazz = clazz.getSuperclass();
            if (superClazz != null) {
                Field[] superFields = superClazz.getDeclaredFields();
                list.addAll(Arrays.asList(superFields));
            }
            return list;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @description: 实体属性转表字段
     * @data: 2020/6/9 16:38
     */
    protected static String propertyToColumn(String property) {
        StringBuilder result = new StringBuilder();
        if (property != null && property.length() > 0) {
            // 将第一个字符处理成大写
            result.append(property.substring(0, 1).toUpperCase());
            // 循环处理其余字符
            for (int i = 1; i < property.length(); i++) {
                String s = property.substring(i, i + 1);
                // 在大写字母前添加下划线
                if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
                    result.append("_");
                }
                // 其他字符直接转成大写
                result.append(s.toUpperCase());
            }
        }
        return result.toString();
    }
}
BatisPlusQueryUtil.java
public class BatisPlusQueryUtil extends BatisPlusUtilLogic {

    /**
     * @description: 加入启用状态的过滤
     * @param columns : 表记为启用的列名称
     * @data: 2020/6/11 09:52
     */
    public static void notContainsDel(QueryWrapper queryWrapper,String...columns){
        for (String column : columns) {
            String columnVal = column.trim();
            if ("".equals(columnVal)){
                continue;
            }
            //PropertiesUtil.LOGIC_NOT_DELETE为已启用的标识状态
            queryWrapper.eq(columnVal, PropertiesUtil.LOGIC_NOT_DELETE);
        }
    }

    public static QueryWrapper getQueryWrapper(Object object) throws IllegalAccessException {
       return getQueryWrapper(object,null,true);
    }

    public static QueryWrapper getQueryWrapper(Object object,boolean isUse) throws IllegalAccessException {
       return getQueryWrapper(object,null,isUse);
    }

    public static QueryWrapper getQueryWrapper(Object object, String ...useColumns) throws IllegalAccessException {
       return getQueryWrapper(object,null,true, useColumns);
    }

    public static QueryWrapper getQueryWrapper(Object object,String group, String ...useColumns) throws IllegalAccessException {
       return getQueryWrapper(object,group,true, useColumns);
    }

    public static QueryWrapper getQueryWrapper(Object object,String group) throws IllegalAccessException {
       return getQueryWrapper(object,group,true);
    }

    public static QueryWrapper getQueryWrapper(Object object, String group, boolean isUse,String ...useColumns) throws IllegalAccessException {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (isUse){
            if (useColumns == null || useColumns.length == 0){
            //PropertiesUtil.LOGIC_DELETE_COLUMN为默认的启用标识列列名
                notContainsDel(queryWrapper, PropertiesUtil.LOGIC_DELETE_COLUMN);
            }else{
                notContainsDel(queryWrapper, useColumns);
            }
        }
        if( object != null) {
            beanToWrapper(object, group, queryWrapper);
        }
        return queryWrapper;
    }
}

业务注解


@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.FIELD)
public @interface NotLike {
    String sourceColumn() default "";
    String[] group() default {};
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.FIELD)
public @interface NotIn {
    String sourceColumn() default "";
    String[] group() default {};
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.FIELD)
public @interface NotBetween {
    String sourceColumn() default "";
    String[] group() default {};
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.FIELD)
public @interface Ne {
    String sourceColumn() default "";
    String[] group() default {};
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.FIELD)
public @interface Lt {
    String sourceColumn() default "";
    String[] group() default {};
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.FIELD)
public @interface LikeRight {
    String sourceColumn() default "";
    String[] group() default {};
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.FIELD)
public @interface LikeLeft {
    String sourceColumn() default "";
    String[] group() default {};
}


@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.FIELD)
public @interface Like {
    String sourceColumn() default "";
    String[] group() default {};
}


@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.FIELD)
public @interface Le {
    String sourceColumn() default "";
    String[] group() default {};
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.FIELD)
public @interface In {
    String sourceColumn() default "";
    String[] group() default {};
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.FIELD)
public @interface Gt {
    String sourceColumn() default "";
    String[] group() default {};
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.FIELD)
public @interface Ge {
    String sourceColumn() default "";
    String[] group() default {};
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.FIELD)
public @interface Eq {
    String sourceColumn() default "";
    String[] group() default {};
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.FIELD)
public @interface Between {
    String sourceColumn() default "";
    String[] group() default {};
}

急用请复制粘贴, 细看劳烦附上建议

多多指教

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值