GORM: Access Properties of Child Object with createAlias()

Use case

Imagine we have a GORM class called Book. This class has an associated Author. And now we want to query certain properties of the author, then we have two common possibilities to perform this query:

HQL, Hibernate Query Language

def myBooks = Book.findAll(" FROM Book as b WHERE b.author.name = :authorName) ", [authorName:"Hermann Hesse"])

With criteria and createAlias

def myBooks = Book.createCriteria().list {     
  createAlias( "author", "a" )    
  eq( 'a.name', "Hermann Hesse" )
}

Side note

I don’t know why the createAlias-method is still not well documented in the Grails documentation – you only find it in the Hibernate documentation.

Tagged with: , , ,
Posted in GORM, Grails, Groovy

Leave a Reply

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

*

Anti-spam protection

Prove that you are Human by typing the emphasized characters:


Protected by Gab Captcha 2

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>