GORM Criteria Query for One-to-Many

In Grails, GORM has some very nice features, not the least of which are Dynamic Finders. It's quite easy to sometimes overlook a really powerful and elegant alternative to dynamic finders in the form of Criteria. In this article I will cover one specific case in which there exists no dynamic finder for a specific use case, but for which a simple, elegant Criteria will do.


Consider the following one-to-many relationship in which One Author has many Books.

   1:class Book{
2: String title
3: static belongsTo = Author
4:}
5:
6:class Author {
7: String name
8: static hasMany = [books: Book]
9:}
The problem: Assuming we are holding a Book object, how do we find the associated Author for that book ? Here's how:
   1:def book = Book.findByTitle('Definitive Guide to Grails')
2:
3:def criteria = Author.createCriteria()
4:
5:def author = criteria {
6: books{
7: eq('id',book.id)
8: }
9:}
The often overlooked "trick" to the above criteria, is the fact that we can use the "books" property on Author in our Criteria to match against (line 6 above).

References:




4 comments:

Hates_ said...

Can you not just say book.author ?

Stephan February said...

Hi hates_

Unfortunately no, not in the way that my model is currently layed out. However it *is* possible with an alternative way of modeling your domain. You can read more about that at this article.

Cheers
Stephan

Hates_ said...

Ahhh! Excellent. I never knew it was possible to do it the way you outlined in the example. Cheers :)

Seymour Cakes said...

You can also do this;

def list = Author.find("from Author auth where ? in elements(auth.books)", book);

Post a Comment