MongoDB MongoTemplate 多条件分页查询

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

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

上图:

Service代码:

public Page<AssetIdentifier> 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<AssetIdentifier> identifierList = mongoTemplate.find(query.with(pageable), AssetIdentifier.class);


    return new PageImpl<AssetIdentifier>(identifierList,pageable,count1);
}
/**
*条件查询
*/
 public List<User> 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("<tr>" +
                    "<th>xxxx</th><th>xxxx</th>" +
                    "<th>xxxx</th><th>xxxx</th>");
                result["content"].forEach(fillAssetIdentifierToPage);

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

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值