16

I have been considering implementing EhCache in my Grails domain objects like this :

static mapping = {
   cache true
}

I am not too familiar with exactly how this caching mechanism works and was wondering what a good rule of thumb is in determining which domain objects would benefit from being cached. eg, objects that are accessed rarely.. often... ?

Thanks!

RyanLynch
  • 2,987
  • 3
  • 35
  • 48

1 Answers1

31

Caching only works for get() calls by default, but queries use the query cache if you update them with cache: true (criteria and HQL).

cache true creates a read-write cache but you can configure a read-only cache with

static mapping = {
   cache usage:'read-only'
}

The read-only cache is good for lookup data that never changes, for example states, countries, roles, etc.

If you have domain classes that update, create, or delete frequently, query caching will often be slower than not caching. This is because changes like these cause all cached queries to be cleared, so you're often going directly to the database anyway. See http://tech.puredanger.com/2009/07/10/hibernate-query-cache/ for a more detailed description of this. For this reason I rarely use query caching and often disable it completely with

hibernate {
    cache.use_second_level_cache=true
    cache.use_query_cache=false
    cache.provider_class='org.hibernate.cache.EhCacheProvider'
}

Domain classes that are "read-mostly" are the best candidates for read-write caching. The caches get cleared for each update, create, and delete, but if these are somewhat rare you'll see an overall performance boost.

Hibernate has an API to monitor cache usage. The http://grails.org/plugin/app-info and http://grails.org/plugin/hibernate-stats plugins make the information available and you can use the approach there in your own code.

Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
  • 1
    Is there a way to get the cache to timeout and re-read? I.e. specify a max-age? Grails caching seems to be very very basic. I see there are a number of ehcache plugins, including "Ehcache Cache Plugin supported by Pivotal", but it is unclear how this will interact or interfere with grails built in domain caching through hibernate through its cache (which appears to also be ehcache). – John Little Jan 28 '15 at 17:21
  • 1
    Hey Burt, Is it possible to segregate the Domain wise cache through hibernate regions ? This will mean an update in one domain does not result in clearing of query cache of all other domains. – Mohd Farid Oct 04 '15 at 18:21