In my view, if I have a situation where I need to use a dynamic method (such as Domain.findByName(“name”)) in multiple places, would it be better to define a variable with and refer to that, rather than have the dynamic method in multiple places? I know this seems like an obvious answer, but I just wanted to make sure Grails doesn’t cache it or something, and indeed two DB calls are being made.
Share
By default, grails will only cache “get” requests (i.e. Book.get(4)), if you don’t set up any additional caching, you’ll hit the database for each request (as you’re seeing).
See the ‘caching queries’ section of the grails documentation for more detail.
If you only want the call to be made once (which makes sense in a view since you’d want it to be consistent), I’d either do the query in the action and pass it in the model, or else you could also use the g:set in your view to set it (though this sounds like it’s more appropriate for a controller or service).