Write Criteria with has many String Types
Taking further this scenario, what if we need to query for partial matches of String, like just ‘rai’ not ‘grails’.
We face many issues while creating criteria with has many relationship on String types as normal way of querying doesn’t work with has many relationship for String types.
One way of getting this done is to use HQL. Above mentioned blog is a very good solution when we need to query for exact match. But what if requirement is to query for partial matches of String. We would modify our HQL to add more complex where clauses, in turn, we would end up writing more complex and error prone HQL.
Solution is to write Alias. Creating criteria is easier and less error prone. Here we can use Alias in Criteria to get this done.
Considering the same example as described in the referred blog:
[java]class Blog {
static hasMany = [tags: String]
} [/java]
createAlias can be used to query for all the blogs containing string ‘grails’ in its tags.
[java]createCriteria().list {
createAlias(‘tags’ , ‘n’)
ilike(‘n.elements’,’%’+tagName+’%’)
}[/java]
PS : This solution works above 2.4.x grails version.
Hope This helps !!