AME
AME

Reputation: 2302

How do I dynamically include expressions in Ebean queries?

I got a search application, where many conditions are combined into a 'and' 'or' list.

Based on user input, some of them can be null, those values shouldn't be considered if they are null.

example:

 public static PagedList<Profile> exampleForSO(String param1, String params2, Integer number, Double d, Boolean condition1, Boolean condition2) {

        return find.where().ieq("param1", param1).
                ieq("param2", params2).
                eq("number", number).
                // based on the fact if condition1 is null include an eq("condition", condition1); block
                // based on the fact if condition2 is null include an eq("condition", condition1); block
            // if param1.equals("test") create an expression .eq("param1", param1).

        findPagedList();
    }

I could probably solve that with a few if else blocks and return the result based on that criteria but there are more than 12 different conditions and therefore a solid way to just exclude them if they are null would be awesome.

I could also create many different methods but there must be some smarter way.

Also the conditions don't have to be null but could have some specific values that makes them obsolete in the query, for example:

params1.equals("something"); 

Don't include it because "something" wouldn't change the search result anyway.

any suggestions?

Upvotes: 2

Views: 641

Answers (1)

KarimBH
KarimBH

Reputation: 11

You can use the object ExpressionList<> returned by find.where() and add conditions dynamicaly.

e.g:

        ExpressionList<Profile> expressionList =  find.where();
        expressionList.ieq("param1", param1);
        expressionList.eq("param2", param2);
        if(condition1){
           expressionList.eq("...", ...);
        }
        if(condition2){
           expressionList.ieq("...", ...);
        }

Best regards

Upvotes: 1

Related Questions