Joar
Joar

Reputation: 224

objectify filter empty values

How can I filter properly using Objectify 4 by several parameters, considering that some of those parameters can come empty, which would mean that I don't want to filter by those? Example: Please consider I want to filter something like this:

      releases = ofy().load().type(Release.class)
                .filter("user.name", searchCriteria.getName())
                .filter("category", searchCriteria.getCategory())
                .filter("city", searchCriteria.getCity()).list();

In order to match with what I said above, I have now the following code, checking every time which of my parameters come empty so I don't put them on the filter in that case:

    if (!nameEmpty && !categoryEmpty && !cityEmpty) {
        releases = ofy().load().type(Release.class)
                .filter("user.name", searchCriteria.getName())
                .filter("category", searchCriteria.getCategory())
                .filter("city", searchCriteria.getCity()).list();
    } else if (!nameEmpty && !categoryEmpty) {
        releases = ofy().load().type(Release.class)
                .filter("user.name", searchCriteria.getName())
                .filter("category", searchCriteria.getCategory()).list();
    } else if (!nameEmpty && !cityEmpty) {
        releases = ofy().load().type(Release.class)
                .filter("user.name", searchCriteria.getName())
                .filter("city", searchCriteria.getCity()).list();
    } else if ...

       ...

How can I avoid this crappy way of filtering and make it with just one line (or a few) using Objectify 4?

Upvotes: 2

Views: 670

Answers (1)

stickfigure
stickfigure

Reputation: 13556

Query<Release> query = ofy().load().type(Release.class);

if (!nameEmpty)
    query = query.filter("user.name", searchCriteria.getName());

if (!categoryEmpty)
    query = query.filter("category", searchCriteria.getCategory())

if (!cityEmpty)
    query = query.filter("city", searchCriteria.getCity());

releases = query.list();

Upvotes: 5

Related Questions