user82302124
user82302124

Reputation: 1143

Grails findAll with like values

Trying to simply run a query of domain objects using find all and it's not acting as I would expect:

searchResults = Contact.findAll("from Contact as c where c.company=${params.company.id} and c.firstName = '%${nameSearch}%'  or c.lastName = '%${nameSearch}%' ")

I want to find all people within a company that have a first name or last name similar to the search that was entered (params.search was stored into nameSearch variable). If I change the value for first or last to a particular name "Tim" or "Johnson", it works.

What am I doing incorrectly with the variable or "like" reference? I thought the % symbol was basically the * symbol in search criteria?

I've tried the 2.0.0 form of search:

        searchResults = Contact.findAll{
            company == params.company.id
            firstName == '%' + nameSearch + '%'
            lastName == '%' + nameSearch + '%'
        }

But that didn't work either. Thank you for all help

Upvotes: 1

Views: 8428

Answers (1)

Rob Hruska
Rob Hruska

Reputation: 120446

Give this a try:

def company = Company.get(params.company.id)
def searchResults = Contact.withCriteria {
    eq('company', company)
    or {
        ilike('firstName', '%' + nameSearch + '%')
        ilike('lastName', '%' + nameSearch + '%')
    }
}

If you don't want to retrieve the Company instance, you could use idEq() within a company { } block instead.


A few things (of perhaps more) that were wrong with your HQL attempt:

  • Your company condition was comparing an object (c.company) to an id value (params.company.id)
  • You needed to group your boolean logic correctly, i.e. (company AND (first OR last)), instead of (company AND first OR last)
  • You should have been using like instead of =, e.g. firstName like '%something%'

As a matter of security, you really, really shouldn't be building your HQL statement with the values inline. You should use named parameters instead. Check out some of the middle examples in the findAll documentation.

Upvotes: 7

Related Questions