Aditya T
Aditya T

Reputation: 1733

How to add multiple 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);

Upvotes: 13

Views: 17523

Answers (2)

Nagaraja JB
Nagaraja JB

Reputation: 753

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

Upvotes: 1

Aditya T
Aditya T

Reputation: 1733

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

Upvotes: 25

Related Questions