MongoDB MongoTemplate 多条件分页查询

最近频繁用到MongoDB,为了加深加深记忆故在此存个档。

需求:初次访问查询全部内容,可在进行条件查询,数据分页展示

上图:

MongoDB MongoTemplate 多条件分页查询_第1张图片

Service代码:

public Page findAllAssetIdentifier(HttpServletRequest request){
    //当前页码 默认给了0
    int page = Integer.parseInt(request.getParameter("page"));
    //页面展示数据条数 默认给了 10
    int count = Integer.parseInt(request.getParameter("count"));
    //筛选条件
    String typeCtg = request.getParameter("type_ctg");
    String type = request.getParameter("type");
    String company = request.getParameter("company");

    //排序
    //Sort sort = Sort.by(Sort.Direction.DESC, "_id");
    //Pageable pageable = PageRequest.of(page, count, sort);
    Pageable pageable = PageRequest.of(page, count);
    Query query = new Query();
    //动态拼接查询条件
    if(StringUtils.isNotBlank(typeCtg)){
        query.addCriteria(Criteria.where("type_ctg").is(typeCtg));
    }
    if(StringUtils.isNotBlank(type)){
        query.addCriteria(Criteria.where("type").is(type));
    }
    if(StringUtils.isNotBlank(company)){
        query.addCriteria(Criteria.where("company").is(company));
    }
    //获取总条数
    long count1 = mongoTemplate.count(query,AssetIdentifier.class);
    LOGGER.debug("asset identifier count:"+count1);
    List identifierList = mongoTemplate.find(query.with(pageable), AssetIdentifier.class);


    return new PageImpl(identifierList,pageable,count1);
}
/**
*条件查询
*/
 public List findUserAll(Principal principal)
            throws ValueInvalidException, SystemErrorException {
        ObjectId tenancyId = getNowUserTenancyID(principal);
        Query query = new Query();
        query.addCriteria(Criteria.where("tenancy_id").is(tenancyId));
        return  mongoTemplate.find(query,User.class);
}

js代码:

function findAllAssetIdentifier(page) {

    $.ajax({
        url:"/asset_identifier/query/",
        method:"POST",
        dataType:"json",
        data:{
            type_ctg:SELECT_ASSET_CATEGORY.val(),
            type:SELECT_ASSET_TYPE.val(),
            company:SELECT_ASSET_COMPANY.val(),
            page:page,
            count:COUNT
        },
        success : function (result) {
            showPage(result["total_pages"],result["number"],"pagination","findAllAssetIdentifier");
            if(result["total_elements"] > 0){
                $("#asset_identifier_body").empty();
                $("#asset_identifier_body").append("" +
                    "xxxxxxxx" +
                    "xxxxxxxx");
                result["content"].forEach(fillAssetIdentifierToPage);

            }else {
                alert("数据为空请导入");
            }
        }
    });
}

 

你可能感兴趣的:(The,path,of,growth)