API / Apache Grails Interview questions
How can you optimize GORM queries to avoid the N+1 problem?
- Use eager fetching with join queries for associations you already know you'll need — a criteria query or HQL with an explicit
joinfetch retrieves the parent and its related records in a single database round trip instead of one query per parent, plus one more per child collection. - Set the fetch strategy on the domain class mapping itself for associations that are almost always needed together, so every query against that class benefits without repeating the join logic at every call site.
- Use projections to retrieve only the specific columns actually needed, rather than hydrating full domain objects (and their lazy associations) when only a couple of fields are actually used.
- Batch-fetch collections using GORM's batch size configuration, which groups the "N" follow-up queries for related collections into fewer, larger queries instead of one query per parent row.
- Profile actual query counts during development (Grails supports SQL logging) rather than guessing, since the N+1 problem is easy to introduce accidentally through an innocent-looking loop over a lazy association and easy to miss without actually looking at the generated SQL.
The underlying discipline is deciding upfront, per query, whether related data is actually needed — and if so, fetching it in the same round trip rather than letting GORM's default lazy-loading trigger a fresh query every time a loop touches an association.
More Related questions...