简体   繁体   中英

Search in every property of domain class

Lets say I have this domain class:

class Person{
  String name
  String street
  String gender
  String foo
  String bar
  ...
}

Is there an easy way to search in every property (so that I just have to call one method to search Persons with name or street or gender ... like String s )?

If not: is there a better way than doing:

Person.findByName(s)
Person.findByStreet(s)
...

An alternative to the answers above is to use criteria.

your code would be as follows

String searchTerm = "something"
def criteria = Person.createCriteria()
def query = {
    or{
      ilike('name', "%${searchTerm}%") //Case insensitive like
      ilike('gender', "%${searchTerm}%")
      ilike('foo', "%${searchTerm}%")
      ilile('bar', "%${searchTerm}%")
      ...
    }       
}

def personInstanceTotal = Documento.createCriteria().count(query) //Returns the filtered count
def personInstanceList = Documento.createCriteria().list(params, query) //May return the paged results

Now you may notice a variable named params . Params is the params map that you normally use in a controller. When working with g:pagination and g:sortableColumn you may get [max:, offset:, order:, sort:] values inside the params map. If you pass these to a criteria you will automatically get some paged results.

This may not look as simple as the other options, but it can be quite flexible when working with more complex querys. There is also the possibility of using ifs inside de query={} declaration, wich can become quite handy.

Using where query:

Person.where {
     name ==~ s || street ==~ s || gender ==~ s || foo ==~ s || bar ==~ s
}.get()

=~ can be used instead of ==~ for case insensitivity.

I would recommend using the grails elastic search plugin

You can make your domain as searchable by adding the property

class Person{
  String name
  String street
  String gender
  String foo
  String bar
  ...
  static searchable = true
}

You can also include/exclude fields

class Person{
  String name
  String street
  String gender
  String foo
  String bar
  ...
  static searchable = {
    except = 'foo'
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM