Sunday, March 20, 2016

Hibernate Cache

Session Cache(1st Level Cache)

1st Level Cache will be pushed during the following functions:
save, update, saveOrUpdate, load, get, list, iterate, lock

1st Level Cache will be loaded during the following functions:
get, load


1st Level Cache cleanning
default enabled, will not auto clean, so do cleaning manually

Example:
session.evict(student); //remove this instance from 1st level cache
session.clear(); //completely clear all instances from the session

Cache Life cycle

All instances will be purged when session closed.


SessionFactory Cache(2st Level Cache)


Stay with SessionFactory, so it's longer than 1st Level.

Has different third-party implementations.

Cache name
Cache Type Provider class
Hashtable
Memory Org.hibernate.cache.HashtableCacheProvider
EHCache
Memory, hard drive Org.hibernate.cache.EhCacheProvider
OSCache(out of maintain)
Memory, hard drive Org.hibernate.cache.OSCacheProvider
SwarmCache
distributed
(no distributed transaction)
Org.hibernate.cache.SwarmCacheProvider
JBoss Cache 1.x
distributed
(distributed transaction)
Org.hibernate.cache.TreeCacheProvider
JBoss Cache 2
distributed
(distributed transaction)
Org.hibernate.cache.JBossCacheRegionFactory


Four usage
1. Use in hibernate.cfg.xml: <class-cache usage="read-write">
2. Use in each *.hbm.xml <cache usage="read-write">

read-only
read-write
nonstrict-read-write
transactional


EHCache Example

hibernate.cfg.xml
  
  <property name="hibernate.generate_statistics">true</property>
  <property name="hibernate.cache.use_structured_entries">true</property>
  <property name="hibernate.cache.use_second_level_cache">true</property>
  <property name="hibernate.cache.use_query_cache">true</property>
  <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
  
  <mapping resource="com/gvace/notebook/domain/User.hbm.xml"/>
  <mapping resource="com/gvace/notebook/domain/Message.hbm.xml"/>
  
  <class-cache usage="read-write" class="com.gvace.notebook.domain.User"/>
  <class-cache usage="read-write" class="com.gvace.notebook.domain.Message"/>
-----------------------------------------------------

ehcache.xml

Optional, customize configs for each model/POJO/domain


2nd Level Cache Statistics

To generate statistics of cache for 2nd Level Cache
  <property name="hibernate.generate_statistics">true</property>

Get statics like follows:

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
System.out.println("AAa"+sessionFactory.getStatistics());

Useful statistics

second level cache puts=10
second level cache hits=0
second level cache misses=0







No comments:

Post a Comment