mybatis-plus 判断参数是否为空并作为查询条件

@Override
    public Page<DemandEntity> selectByDepartmentDisplay(DemandEntity demandEntity) {
        EntityWrapper<DemandEntity> wrapper = new EntityWrapper<DemandEntity>();
        wrapper.eq(!StringUtils.isNullOrEmpty(demandEntity.getNameDemandDepartmentDispaly()),"name_demand_department_dispaly",demandEntity.getNameDemandDepartmentDispaly());
        Page<DemandEntity> demandEntityPage = this.selectPage(demandEntity.getPages(),wrapper);
        return demandEntityPage;
    }

 只需要在eq条件构造器中只需要添加 一句判断即可:

!StringUtils.isNullOrEmpty(demandEntity.getNameDemandDepartmentDispaly() 为true,就拼接where条件;为Flase就不拼接;

 eq(boolean condition, R column, Object val)     第一个参数 为boolean类型 true就拼接上 flase就不拼接;

其中 StringUtils.isNullOrEmpty()方法,作用是:

判断对象或对象数组中每一个对象是否为空: 对象为null,字符序列长度为0,集合类、Map为empty;

并附上 isNullOrEmpty() 源码;

/**
     * 判断对象或对象数组中每一个对象是否为空: 对象为null,字符序列长度为0,集合类、Map为empty
     *
     * @param obj
     * @return
     */
    public static boolean isNullOrEmpty(Object obj) {

        if (obj == null) return true;

        if (obj instanceof CharSequence) return ((CharSequence) obj).length() == 0;

        if (obj instanceof Collection) return ((Collection) obj).isEmpty();

        if (obj instanceof Map) return ((Map) obj).isEmpty();

        if (obj instanceof Object[]) {
            Object[] object = (Object[]) obj;
            if (object.length == 0) {
                return true;
            }
            boolean empty = true;
            for (int i = 0; i < object.length; i++) {
                if (!isNullOrEmpty(object[i])) {
                    empty = false;
                    break;
                }
            }
            return empty;
        }

        return false;
    }

---【拓展】---

  • eq

eq(R column, Object val)
eq(boolean condition, R column, Object val)

  • 等于
  • 例: eq(“name”, “老王”) 等价于  name = ‘老王’
发布了85 篇原创文章 · 获赞 197 · 访问量 33万+

猜你喜欢

转载自blog.csdn.net/weixin_43970743/article/details/98621712