美文网首页
springboot进行mongo模糊查询

springboot进行mongo模糊查询

作者: Mark_ZSQ | 来源:发表于2020-12-02 20:06 被阅读0次
    @Override
    public ResultModel getGateWayPageList(PageModel pageModel) {
        log.info("getGateWayPageList --> {}");
        JSONObject paramJson = (JSONObject) pageModel.getSearchData();
        Integer manufacturerId = paramJson.getInteger("manufacturerId");
        Integer status = paramJson.getInteger("status");
        String name = paramJson.getString("name");

        int pageNum = pageModel.getPageNum();
        int pageSize = pageModel.getPageSize();

        // 构造查询条件
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(pageNum, pageSize, sort);


        //动态拼接查询条件
        QueryBuilder queryBuilder = new QueryBuilder();
        queryBuilder.and("type").is(TypeEnum.DEVICE_GATEWAY.getKey());
        if (StringUtils.isNotEmpty(name)) {
            Pattern pattern = Pattern.compile("^.*" + name + ".*$", Pattern.CASE_INSENSITIVE);
            queryBuilder.and("name").regex(pattern);
        }

        if (null != manufacturerId) {
            queryBuilder.and("manufacturerId").is(manufacturerId);
        }
        if (null != status) {
            queryBuilder.and("status").is(status);
        }

        Query query = new BasicQuery(queryBuilder.get().toString());
        //计算总数
        long total = mongoTemplate.count(query, JSONObject.class);

        //查询结果集条件
        BasicDBObject fieldsObject = new BasicDBObject();
        //id默认有值,可不指定     1查询,返回数据中有值;0不查询,无值
        fieldsObject.append("name", 1);
        query = new BasicQuery(queryBuilder.get().toString());

        //查询结果集
        List<GateWay> gateWayList = mongoTemplate.find(query.with(pageable), GateWay.class);
        Page<GateWay> studentPage = new PageImpl(gateWayList, pageable, total);
        return ResultModelUtils.getSuccessInstance(studentPage);
    }

相关文章

网友评论

      本文标题:springboot进行mongo模糊查询

      本文链接:https://www.haomeiwen.com/subject/zeiuwktx.html