gunboxer
gunboxer

Reputation: 49

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.

Upvotes: 0

Views: 337

Answers (2)

injecteer
injecteer

Reputation: 20699

you can apply the sugar right on the arguments map (assuming filter is a Map):

def args = filter.collectEntries{ k, v -> 
  [ 'age', 'name', 'department' ].contains( k ) && v ? [ (k):v ] : Collections.EMPTY_MAP 
}
def users = User.findAll args

Upvotes: 0

Stefan Urbansky
Stefan Urbansky

Reputation: 148

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)
}

Upvotes: 2

Related Questions