简体   繁体   English

如何向 Spring Data 中的条件添加多个 AND 条件

[英]How to add mulitple AND conditions to criteria in Spring Data

I am trying to add multiple 'and' conditions to criteria in Spring Data but not able to figure out what am I doing wrong.我正在尝试向 Spring Data 中的条件添加多个“和”条件,但无法弄清楚我做错了什么。 Please refer the following code :请参考以下代码:

Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("siteCode").is(siteCode));

        if(paymentMode != null) {
            criteria.andOperator(Criteria.where("paymentMode").is(paymentMode));
        }
        if(planCode != null) {
            criteria.andOperator(Criteria.where("packageCode").is(planCode));
        }
        if(status){
            criteria.andOperator(Criteria.where("expiryDateTime").gt(new Date()));
        } else {
            criteria.andOperator(Criteria.where("expiryDateTime").lte(new Date()));
        }

        Query query = new Query(criteria);

        List<UserPackage> userPackageList = mongoTemplate.find(query, UserPackage.class);

I found out what I was doing wrong.我发现我做错了什么。 You don't need to use method 'andOperator' and another Criteria inside.您不需要在内部使用方法“andOperator”和另一个 Criteria。

It would simply work by using 'and' method and then chain the following operator method you want to use.它只需使用“and”方法,然后链接您要使用的以下运算符方法即可。

Sharing the working solution to help other newcomers like me.分享工作解决方案以帮助像我这样的其他新人。

        Criteria criteria = new Criteria();
        criteria = criteria.and("siteCode").is(siteCode);
        if (paymentMode != null) {
            criteria = criteria.and("paymentMode").is(paymentMode);
        }
        if (planCode != null) {
            criteria = criteria.and("packageCode").is(planCode);
        }
        if (status) {
            criteria = criteria.and("expiryDateTime").gt(new Date());
        } else {
            criteria = criteria.and("expiryDateTime").lte(new Date());
        }
        Query query = new Query(criteria);

Just in case if you want to add conditions for a date between and match another field, below is what I used.以防万一,如果您想为另一个字段之间的日期添加条件并匹配另一个字段,下面是我使用的。

    Criteria criteria = Criteria.where("date").gte(from).andOperator(Criteria.where("date").lt(to));

    if (StringUtils.isNotBlank(manager)) {
        criteria = criteria.and("manager").is(manager);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM