Reputation: 14539
I wrote the following piece of code to do selective queries, but it doesn't seem to be working.
public static List<Item> selectBy(String name, String attr) {
Query<Item> find = myFinderInstance;
if (name != null) {
find.where().eq("name", name);
}
if (attr != null) {
find.where().eq("attr", attr);
}
return find.findList();
}
Basically I want the query to be able to work together. Either only by name, only by attribute or both. But with only 1 function.
Is this not possible or am I doing it wrong?
Upvotes: 1
Views: 534
Reputation: 55798
You can add params conditionally to the ExpressionList
, in this case if all params will be null it will return ALL objects:
import com.avaje.ebean.ExpressionList;
import static com.avaje.ebean.Expr.eq;
// ...
public static List<Item> findByNameAndAttr(String name, String attr) {
ExpressionList<Item> myQuery = find.where();
if (name != null) myQuery.add(eq("name", name));
if (attr != null) myQuery.add(eq("attr", attr));
return myQuery.findList();
}
optionally if you prefer empty set if both params are null
just start your method with condition:
if (name == null && attr == null) return new ArrayList<>();
Upvotes: 2