gunboxer gunboxer - 13 days ago 5
Groovy Question

Groovy domain class find with only provided filter

Hello

I need to perform Domain class filtering in Groovy for provided filter fields.
Here is code sample:

User.findAll(name: filter.name, age: filter.age, department: filter.department)


Is there exists some syntax sugar to help me to validate if for example filter.name is not provided e.g. null or empty - do not filter by this field. Thanks.

Answer

Abs has right. Here is an example with if-statements for not provided filter fields:

User.createCriteria().list {
  if (filter.name)       eq("name", filter.name)
  if (filter.age)        eq("age", filter.age)
  if (filter.department) eq("department", filter.department)
}