Following is an example of unidirectional one-to-many relationship:
class Employee { String name static hasMany = [roles: Role] } class Role { String name }
How can we find all the employees with a particular role – “Grails Developer”?
Role role = Role.findByName("Grails Developer")
One way of doing this can be:
Employee.list().findAll{role in it.roles}
This is an inefficient way since, we are fetching all the records from the database every time. Also, in case we are showing paginated view of results, we will need to manage pagination ourself.
A better way of this will be using createCriteria() query:
List<Employee> employees = Employee.createCriteria().list{ roles{ eq('id', role.id) } firstResult(20) maxResults(20) }
I am wondering what will be the query in case Role.groovy is an enum.
–
~Aman Aggarwal
aman@intelligrape.com
http://www.IntelliGrape.com/
This entry was posted
on June 14th, 2010
at
3:22 pm and is filed under
Database, Grails .
You can follow any responses to this entry through the
RSS 2.0 feed.
You can leave a response, or trackback from your own site.

you should use aliases for this.. it is explained here:
http://adhockery.blogspot.com/2009/06/querying-by-association-redux.html
Thanks!