1.4.2.2. Configure the entity beans for cache

1.4.2.2. Configure the entity beans for cache

You define your entity bean classes the normal way. Future versions of JBoss EJB 3.0 will support annotating entities and their relationship collections as cached, but for now you have to configure the underlying hibernate engine directly. Take a look at the persistence.xml file, which configures the caching options for hibernate via its optional property elements. The following element in persistence.xml defines that caching should be enabled:

<!-- Clustered cache with TreeCache -->
<property name="cache.provider_class">
    org.jboss.ejb3.entity.TreeCacheProviderHook
</property>
                

The following property element defines the object name of the cache to be used, and the MBean name.

<property name="treecache.mbean.object_name">
    jboss.cache:service=EJB3EntityTreeCache
</property>
                

Next we need to configure what entities be cached. The default is to not cache anything, even with the settings shown above. We use the @Cache annotation to tag entity beans that needs to be cached.

@Entity 
@Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL) 
public class Customer implements Serializable { 
  // ... ... 
}
                

A very simplified rule of thumb is that you will typically want to do caching for objects that rarely change, and which are frequently read. You can fine tune the cache for each entity bean in the ejb3-entity-cache-service.xml configuration file. For instance, you can specify the size of the cache. If there are too many objects in the cache, the cache could evict oldest objects (or least used objects, depending on configuration) to make room for new objects. The cache for the mycompany.Customer entity bean is /mycompany/Customer cache region.

<server>  
  <mbean code="org.jboss.cache.TreeCache" 
         name="jboss.cache:service=EJB3EntityTreeCache">  
    <depends>jboss:service=Naming 
    <depends>jboss:service=TransactionManager 
    ... ... 
    <attribute name="EvictionPolicyConfig">  
      <config>  
        <attribute name="wakeUpIntervalSeconds">5</attribute>  
        <region name="/_default_">  
          <attribute name="maxNodes">5000</attribute>  
          <attribute name="timeToLiveSeconds">1000</attribute>  
        </region>  
        <region name="/mycompany/Customer">  
          <attribute name="maxNodes">10</attribute>  
          <attribute name="timeToLiveSeconds">5000</attribute>  
        </region>  
        ... ... 
      </config>  
    </attribute>  
  </mbean> 
</server>
                

If you do not specify a cache region for an entity bean class, all instances of this class will be cached in the /_default region as defined above. The EJB3 Query API provides means for you to save to load query results (i.e., collections of entity beans) from specified cache regions.