Showing posts with label criteria. Show all posts
Showing posts with label criteria. Show all posts

20 March 2008

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: