Second Level Caching in Hibernate with ehcache

Need to configure hibernate properties

<prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop>
<prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>

POJO need to be marked as Cache

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY,region = "country")
@Table(name = "tbl_Country", schema = "dbo", catalog = "student")
public class TblCountry implements java.io.Serializable {

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?> 
<ehcache>
<defaultCache maxElementsInMemory="100" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="200" />
<cache name="country" maxElementsInMemory="100" eternal="false" timeToIdleSeconds="5" timeToLiveSeconds="200" />
</ehcache>

TestClass here a sleep of 6 sec is placed so ehcache make a hit as its timeToIdleSeconds is 5.


package taher.javahunter;

import org.hibernate.Session;
import pojo.TblCountry;
import sessionfactory.HibernateUtil;

/**
 *
 * @author taher.tinwala
 */
public class TestClas {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        TblCountry country = (TblCountry) session.load(TblCountry.class, new Integer(26));
        System.out.println(country.getCountryName());
        session.close();
        try {
            Thread.sleep(6000);
        } catch (Exception e) {
        }
        Session session2 = HibernateUtil.getSessionFactory().openSession();
        TblCountry country1 = (TblCountry) session2.load(TblCountry.class, new Integer(26));
        System.out.println(country1.getCountryName());
        session2.close();        
        Session session3 = HibernateUtil.getSessionFactory().openSession();
        TblCountry country2 = (TblCountry) session3.load(TblCountry.class, new Integer(26));
        System.out.println(country2.getCountryName());
        session3.close();        
        HibernateUtil.getSessionFactory().close();
    }
}
Output :

Here ehcahe.xml has country cached for 5 secs
Hibernate: select tblcountry0_.countryId as countryId0_0_, tblcountry0_.countryCode as countryC2_0_0_, tblcountry0_.countryName as countryN3_0_0_ from student.dbo.tbl_Country tblcountry0_ where tblcountry0_.countryId=?
Srilanka
Hibernate: select tblcountry0_.countryId as countryId0_0_, tblcountry0_.countryCode as countryC2_0_0_, tblcountry0_.countryName as countryN3_0_0_ from student.dbo.tbl_Country tblcountry0_ where tblcountry0_.countryId=?
Srilanka
Srilanka

Here ehcahe.xml has country cached for 7 secs
Hibernate: select tblcountry0_.countryId as countryId0_0_, tblcountry0_.countryCode as countryC2_0_0_, tblcountry0_.countryName as countryN3_0_0_ from student.dbo.tbl_Country tblcountry0_ where tblcountry0_.countryId=?
Srilanka
Srilanka
Srilanka

Annotations to be placed on POJO’s

@Entity
@Table(name = "tbl_LoginMaster", schema = "dbo")
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class TblLoginMaster  implements java.io.Serializable {
...
...
}
//2nd Level Caching while creating HQL
public List getStreetTypes(final Country country) throws HibernateException {
final Session session = createSession();
try {
   final Query query = session.createQuery(
    "select st.id, st.name"
   + " from StreetType st "
   + " where st.country.id = :countryId "
   + " order by st.sortOrder desc, st.name");
   query.setLong("countryId", country.getId().longValue());
   query.setCacheable(true);
   query.setCacheRegion("query.StreetTypes");
   return query.list();
} finally {
   session.close();
}
}
Advertisements
This entry was posted in Hibernate, Spring. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s