Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 889
Aditya T Avatar asked Aug 15 '16 18:08

Aditya T


2 Answers

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);
like image 61
Aditya T Avatar answered Nov 18 '22 07:11

Aditya T


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);
    }
like image 33
Nagaraja JB Avatar answered Nov 18 '22 08:11

Nagaraja JB