JPA Caching
For optimization of an existing application, it is very useful caching catalog data and master data.
Unlike transaction data, which refer to certain processes and are needed in certain usecases, master data are involved in nearly every process.
So it is clever to thing about caching these data.
So called key data or catalog data have in common that they are read all the time, but nearly never changed.
How can caching strategies with JPA / Hibernate can be done?
Activation of the Hibernate Second Level Caches
Configuration of the cache provider
Filtering of the cache candidates and tagging the entities / associations.
1. Activation of the Hibernate Second Level Caches
In the persistence.xml or hibernate.cfg.xml the property hibernate.cache.use_second_level_cache must be set to true.
With that besides the first level cache, which is in charge of all managed entities of the according hibernate session, a second cache in hibernate is activated, which works beyond transactions.
The first level cache is bound to the actual transaction and is cleared as soon as the transaction is terminated(committed).
The second level cache is not bound to the hibernate session, it is bound to the entity manager / HibernateSessionFactory.
Thus entities can be handed out without a callback to the database has to be done, if the entities are not loaded in the actual transaction, but a transaction before has already loaded/written those entities.
2. Configuration of the cache provider
Hibernate has an own implementation for the second level cache.
But this is only a test implementation and should never be used for productive use.
Therefore one must select the according cache provider and this should be set in the configuration:
hibernate.cache.region.factory_class
There are some cache provider: JBoss Cache, Infinispan, ...
Infinispan will be the official cache provider in JBoss and is highly in use.
The introduction of regions(Interface region.factory_class) is new:
There is a possibility for caching query results.
Rules and approach for such a cache differs from an application wide Second-Level-Cache, who caches entities beyond transactions.
Thus the second level cache can be divided in different regions in order for configuring certain cache mechanism, eviction policies etc.
3. Filtering of the cache candidates and tagging the entities / associations.
In order to cache an entity by hibernate, it must be annotated with
@org.hibernate.annotations.Cache respectively JPA @javax.persistence.Cacheable
An association must be annotated with @org.hibernate.annotations.Cache in the according getter method of the involved entity.
Following book copes with Caching and Query Cache(see chapter 9):
Nice Blog, When i was read this blog i learnt new things & its truly have well stuff related to developing technology, Thank you for sharing this blog.
ReplyDeleteios course fee in bangalore
iphone training classes in bangalore