简体   繁体   中英

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. 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.

It would simply work by using 'and' method and then chain the following operator method you want to use.

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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