Grails: Lessons Learned (James Lorenzen)
Grails, James Lorenzen July 21st, 2008
James Lorenzen writes about two some lessons he has learned while working with Grials and One-to-many relationships. The first one is related to eager vs lazy fetching of collections. James writes:
I by no means am a grails expert, but based on my experience don’t set the eager fetching in your Domain as the example shows (unless you have a very good reason and understand the consequences). Lazy vs Eager fetching is well described in the grails documentation, so I won’t repeat it, but anyone using One-to-many relationships needs to know the differences.
The default behavior in grails is lazy fetching, which results in n+1 queries. In some cases this might be ideal, in others it may not. When it’s not you have a couple of choices. The example in the grails documentation sets a fetchMode property on the Domain. This sets it globally and every time the Domain is accessed, grails is going to load all it’s many relationships. The path I recommend is to specify the fetch mode when retrieving the data. For example, the list() method has a parameter called fetch and can be used like this: Book.list(fetch: [authors: “eager”]). This gives you the most flexibility by not specifying the fetch mode globally, but allowing you to fetch eagerly when necessary.
The second lesson is related to child deletion from a parent’s collection, we are sure other developers have encountered this problem before, int this case James solved it by piggybacking on Hibernate Events. In order to effectively delete a child you need to remove it form the parent’s collection and call delete() on it, so instead of writing two lines of code everywhere you just define a beforeDelete event handler in the Child domain class. James writes:
The hibernate events are interesting. By default grails supports 4 events: beforeInsert, beforeUpdate, beforeDelete, onLoad. However, there is a recent plugin called Hibernate Events Plugin that adds 7 more events: beforeLoad, afterLoad, beforeSave, afterSave, afterInsert, afterUpdate, afterDelete.
Tags: Grails, James Lorenzen
About