Question

I have a search form use to search houses in my web application. Form has the following fields,

private String type;
private Long minPrice;
private Long maxPrice;
private Integer minBedRooms;

This form is use to search houses when use enter data into all the fields. For example user enter data "Rent 200 5000 2" in all fields respectively. My query for this is

Query query = new Query(where("type")
            .is(form.getType())
            .and("bedrooms")
            .is(form.getMinBedRooms())
            .andOperator(where("price").lte(form.getMaxPrice()),
                    where("price").gte(form.getMinPrice())));

NOW when i leave one of the above fields empty, it returns 0 results. For example when maxPrice is null, it returns 0 results. My question is how should i write the above query so that it can igone the null values. For example, i leave the maxPrice and minBedRooms fields empty the it will search data based on the type and minPrice

I am using spring 4. and spring data with mongoDB

I have been stuck with this for two days, I shall be very thankful for any kind of help. Regards,

Was it helpful?

Solution

The following for is equivalent, but adding the logic tests around it

  Query query = new Query();

  if (form.getType() != null) {
      query.addCriteria(Criteria.where("type")
        .is(form.getType());
  }

  if (form.getMinBedrooms() != 0) {
        query.addCriteira(Criteria.where("bedrooms")
        .is(form.getMinBedRooms())
  }

And so on. So just work with the Query object and add your conditions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top