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:}
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:}
References:
- The GORM section of the Grails User Guide