Dynamic finders rock! But if you’re querying across tricky many-to-many joins, you might want to take advantage of GORM’s extremely powerful query DSL, criteriaBuilder.

Criteria wraps Hibernate’s powerful Restrictions API, and gives you a wealth of expressiveness. For the Gravl archive, I wanted a “by tag” archive option, so you could see just the “groovy-related” archive. Because blog entries have a many to many with blog tags, dynamic finders weren’t going to get me there.

CriteriaBuilder will let me do stuff like “find all blog entries that are attached to this blog object, have a status of published, and contain a tag object in their tags collection where the tag name is groovy. Give me a max of 20 objects for my archive page, and offset it with whatever the paginate tags says we’re up to”:

def bc = BlogEntry.createCriteria()
def entries = bc.list {
    eq('blog', blog)
    eq('status', 'published')
    tags {
        eq('name', params.tagName)
    }
    maxResults(20)
    firstResult(offset)
    order("created", "desc")
}

Using the firstResult to be your g:paginate offset, and you’ve got yourself a scrollable, by-category archive to link up to your tagcloud. And we’re in action…

The Groovy Related Archive

You can also also use Criteria to do counting (and even recordset scrolling!). Check out the docs for more details. I know I’ll be using Criteria lot more now that I’ve tasted how simply you can express complex queries.

GORM rocks!