I've been trying to add search functionality to my grails project and I'm running into a bit of a snag.
Here's my domain class
class Worker{
String name
}
and here's my controller
package main
class SiteController {
def search()
{
def results = Worker.findAll{
it.name ==~ /.*John.*/
}
[results:results]
}
}
I'm trying to figure out how to use the findAll(closure) function, but I can't find examples anywhere and I can't seam to figure it out via testing either, I just want to find all of the workers by the test criteria I put in the closure.
EDIT 1
I'm having another problem, for some reason whenever I use any special characters in my regex, such as [. * ?] or any of those, my findAll doesn't return anything. If I have a workers whose name is "John Smith" and I do
name ==~ /John Smith/
it works as it should, but if I use any of those special characters such as
name ==~ /John.*/
or even
name ==~ /John S.ith/
it won't work, this is very confusing and the regexs works as they should right outside the findall function too, if you could provide some insight into this that'd be very helpful
Use LIKE in query instead, Try this:
results = Person.findAllByLastNameLike("%John%")
Grails uses hibernate underneath which uses HQL language which is similar to SQL. Alternatively, you can also run full query
results = Person.findAll("from Person as p where p.lastName LIKE :lastname order by p.lastName", [lastname: '%John%'])
To look for into HQL queries: http://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/queryhql.html
And it is sad but true, HQL/SQL doesn't support regular expressions, it only supports LIKE clause.