Question

Im trying cache-ehcache plugin for grails which seems pretty easy to set up and work with! However, if I read the documentation correctly following should work and return cached results:

DataSource.groovy:

hibernate {
  cache.use_second_level_cache = true
  cache.use_query_cache = true
  cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}

Config.groovy:

grails.cache.config = {
  domain {
    name 'com.mycompany.User'
  }
}

MyClass:

User.findByMyField("myVal", [cache:true])

But it doesn't work for me unless I also add following to User.groovy

static mapping = {
    cache true
}

I was under impression that changes to User were not necessary as this is what "domain{}" block in Config.groovy was defining, but I just cannot get it to work without it otherwise.

I really want to avoid modifying User.class as it's used across multiple projects that I don't want to be affected!

Any suggestions would be appreciated!

Was it helpful?

Solution

The domain method in the DSL is just an alias to make the configuration more intuitive, but it doesn't affect whether the domain class is cached, just how it's cached when it's enabled. You still need to enable caching overall with cache.use_second_level_cache = true, and configure caching in the domain classes.

2nd-level caching in Hibernate is interface-based, and most of the real work is done by the implementation that you choose. So you need to get things started in Hibernate, and GORM uses the cache method in the mapping block to do this, but then you need to do the implementation-specific configuration to tune the caching, and that's where you need to work with the Ehcache API directly, or indirectly, e.g. via this DSL.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top