Setting up caching

Hibernate features a second-level cache with a customizable cache provider. This needs to be configured in the grails-app/conf/DataSource.groovy file as follows:

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

You can of course customize these settings how you desire, for example if you want to use a distributed caching mechanism.

For further reading on caching and in particular Hibernate's second-level cache, refer to the Hibernate documentation on the subject.

Caching instances

In your mapping block to enable caching with the default settings use a call to the cache method:

class Person {
  ..
  static mapping = {
      table 'people'
      cache true
  }
}

This will configure a 'read-write' cache that includes both lazy and non-lazy properties. If you need to customize this further you can do:

class Person {
  ..
  static mapping = {
      table 'people'
      cache usage:'read-only', include:'non-lazy'
  }
}

Caching associations

As well as the ability to use Hibernate's second level cache to cache instances you can also cache collections (associations) of objects. For example:

class Person {
  String firstName
  static hasMany = [addresses:Address]
  static mapping = {
      table 'people'
      version false
      addresses column:'Address', cache:true
  }
}
class Address {
   String number
   String postCode
}

This will enable a 'read-write' caching mechanism on the addresses collection. You can also use:

cache:'read-write' // or 'read-only' or 'transactional'

To further configure the cache usage.

Caching Queries

You can cache queries such as dynamic finders and criteria. To do so using a dynamic finder you can pass the cache argument:

def person = Person.findByFirstName("Fred", [cache:true])

Note that in order for the results of the query to be cached, you still need to enable caching in your mapping as discussed in the previous section.

You can also cache criteria queries:

def people = Person.withCriteria {
	like('firstName', 'Fr%')
	cache true
}

Cache usages

Below is a description of the different cache settings and their usages: