Grails criteria query example for unidirectional one-to-many relationships

14 / Jun / 2010 by Aman Aggarwal 1 comments

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 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.tothenew.com/blog/

FOUND THIS USEFUL? SHARE IT

comments (1 “Grails criteria query example for unidirectional one-to-many relationships”)

  1. John Rellis

    you should use aliases for this.. it is explained here:

    adhockery.blogspot.com/2009/06/querying-by-association-redux.html

    Thanks! 🙂

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *