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

x33g5p2x  于2022-05-25 转载在 其他  
字(1.7k)|赞(0)|评价(0)|浏览(272)

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

@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 = ‘老王’

查询时某些字段为null的问题

在SpringBoot+Mybatis项目执行时发现,Mybatis查询的数据中的某些字段为null

在网站上搜索得到的是mybatis配置中需要添加一段配置驼峰命名法
mybatis:configuration:map-underscore-to-camel-case: true

但在公司项目中这个配置是已经配置的了,经过测试还是无法获取正确的值

经过自己查看代码后发现,是字段无法映射到对应的实体上,即charging_name(entity)->charging_name(database)

将实体类的charging_name修改为chargingName,开启驼峰命名法,就可以获取正确的值了。

相关文章