Grails wildcard search on two fields
So I’m still in learning mode w/Groovy & Grails, and I have basic CRUD for managing users. The user domain class has the properties that you’d expect, including a FirstName and LastName:
class User { String firstName String lastName }
So I wanted to create a simple right side wildcard search that would effectively be the same as this in SQL Server:
where (firstName like '#searchTerm#%' or lastName like '#searchTerm#%')
In Grails you have a wrapper around Hibernate called GORM, which provides a mechanism called Dynamic Finders.
Imagine if you had to write a collection of functions for finding and retrieving one or many records based on each property (findByFirstName(), findAllByFirstName(), findFirstNameLike(), findByAgeGreaterThan(), etc…), it could take awhile. 🙂
But with GORM, it’s as if a little elf in the middle of the night coded all night long to create these functions for you. You never see them, but they’re magically there!
There’s a whole “with criteria” mechanism and the Hibernate Query Language (HQL), but I found the simplest way was just to do this:
def userList =
User.findAllByFirstNameLikeOrLastNameLike("${params.searchTerm}%", "${params.searchTerm}%")
Leave a Comment