Red Hat Training

A Red Hat training course is available for Red Hat JBoss Web Server

20.2. The Second Level Cache

A Hibernate Session is a transaction-level cache of persistent data. It is possible to configure a cluster or JVM-level (SessionFactory-level) cache on a class-by-class and collection-by-collection basis. You can even plug in a clustered cache. Be aware that caches are not aware of changes made to the persistent store by another application. They can, however, be configured to regularly expire cached data.
You have the option to tell Hibernate which caching implementation to use by specifying the name of a class that implements org.hibernate.cache.CacheProvider using the property hibernate.cache.provider_class. Hibernate is bundled with a number of built-in integrations with the open-source cache providers that are listed below. You can also implement your own and plug it in as outlined above.

Table 20.1. Cache Providers

CacheProvider classTypeCluster SafeQuery Cache Supported
Hashtable (not intended for production use)org.hibernate.cache.HashtableCacheProvidermemory yes
EHCacheorg.hibernate.cache.EhCacheProvidermemory, disk yes
OSCacheorg.hibernate.cache.OSCacheProvidermemory, disk yes
SwarmCacheorg.hibernate.cache.SwarmCacheProviderclustered (ip multicast)yes (clustered invalidation) 
JBoss Cache 1.xorg.hibernate.cache.TreeCacheProviderclustered (ip multicast), transactionalyes (replication)yes (clock sync req.)
JBoss Cache 2org.hibernate.cache.jbc2.JBossCacheRegionFactoryclustered (ip multicast), transactionalyes (replication or invalidation)yes (clock sync req.)

20.2.1. Cache mappings

The <cache> element of a class or collection mapping has the following form:
<cache 
    usage="transactional|read-write|nonstrict-read-write|read-only"   1
    region="RegionName"                                               2
    include="all|non-lazy"                                            3
/>

1

usage (required) specifies the caching strategy: transactional, read-write, nonstrict-read-write or read-only

2

region (optional: defaults to the class or collection role name): specifies the name of the second level cache region

3

include (optional: defaults to all) non-lazy: specifies that properties of the entity mapped with lazy="true" cannot be cached when attribute-level lazy fetching is enabled
Alternatively, you can specify <class-cache> and <collection-cache> elements in hibernate.cfg.xml.
The usage attribute specifies a cache concurrency strategy.