About Alex Soto

Hibernate cache levels tutorial

One of the common problems of people that start using Hibernate is performance, if you don’t have much experience in Hibernate you will find how quickly your application becomes slow. If you enable sql traces, you would see how many queries are sent to database that can be avoided with little Hibernate knowledge. In current post I am going to explain how to use Hibernate Query Cache to avoid amount of traffic between your application and database.

Hibernate offers two caching levels:

  • The first level cache is the session cache. Objects are cached within the current session and they are only alive until the session is closed.
  • The second level cache exists as long as the session factory is alive. Keep in mind that in case of Hibernate, second level cache is not a tree of objects; object instances are not cached, instead it stores attribute values.

After this brief introduction (so brief I know) about Hibernate cache, let’s see what is Query Cache and how is interrelated with second level cache.

Query Cache is responsible for caching the combination of query and values provided as parameters as key, and list of identifiers of objects returned by query execution as values. Note that using Query Cache requires a second level cache too because when query result is get from cache (that is a list of identifiers), Hibernate will load objects using cached identifiers from second level.

To sum up, and as a conceptual schema, given next query: “from Country where population > :number“, after first execution, Hibernate caches would contain next fictional values (note that number parameter is set to 1000):

L2 Cache
[
id:1, {name=’Spain’, population=1000, ….}
id:2, {name=’Germany’, population=2000,…}
….
]
QueryCache
[{from Country where population > :number, 1000}, {id:2}]

So before start using Query Cache, we need to configure cache of second level.
First of all you must decide what cache provider you are going to use. For this example Ehcache is chosen, but refer to Hibernate documentation for complete list of all supported providers.

To configure second level cache, set next Hibernate properties:

hibernate.cache.provider_class = org.hibernate.cache.EhCacheProvider
hibernate.cache.use_structured_entries = true
hibernate.cache.use_second_level_cache = true

And if you are using annotation approach, annotate cachable entities with:

@Cacheable
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)

See that in this case cache concurrency strategy is NONSTRICT_READ_WRITE, but depending on cache provider, other strategies can be followed like TRANSACTIONAL, READ_ONLY, … take a look at cache section of Hibernate documentation to chose the one that fits better with your requirements.

And finally add Ehcache dependencies:

<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>3.6.0.Final</version>
</dependency>

Now second level cache is configured, but not query cache; anyway we are not far from our goal.

Set hibernate.cache.use_query_cache property to true.

And for each cachable query, we must call setCachable method during query creation:

List<Country> list = session.createQuery(“from Country where population > 1000″).setCacheable(true).list();

To make example more practical I have uploaded a full query cache example with Spring Framework. To see clearly that query cache works I have used one public database hosted in ensembl.org. The Ensembl project produces genome databases for vertebrates and other eukaryotic species, and makes this information freely available online. In this example query to dna table is cached.

First of all Hibernate configuration:

@Configuration
public class HibernateConfiguration {

 @Value("#{dataSource}")
 private DataSource dataSource;

 @Bean
 public AnnotationSessionFactoryBean sessionFactoryBean() {
  Properties props = new Properties();
  props.put("hibernate.dialect", EnhancedMySQL5HibernateDialect.class.getName());
  props.put("hibernate.format_sql", "true");
  props.put("hibernate.show_sql", "true");
  props.put("hibernate.cache.provider_class", "org.hibernate.cache.EhCacheProvider");
  props.put("hibernate.cache.use_structured_entries", "true");
  props.put("hibernate.cache.use_query_cache", "true");
  props.put("hibernate.cache.use_second_level_cache", "true");
  props.put("hibernate.hbm2ddl.auto", "validate");

  AnnotationSessionFactoryBean bean = new AnnotationSessionFactoryBean();
  bean.setAnnotatedClasses(new Class[]{Dna.class});  
  bean.setHibernateProperties(props);
  bean.setDataSource(this.dataSource);
  bean.setSchemaUpdate(true);
  return bean;
 }

}

It is a simple Hibernate configuration, using properties previously explained to configure second level cache.

Entity class is an entity that represents a sequence of DNA.

@Entity(name="dna")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Dna {

 @Id
 private int seq_region_id;

 private String sequence;

 public int getSeq_region_id() {
  return seq_region_id;
 }

 public void setSeq_region_id(int seq_region_id) {
  this.seq_region_id = seq_region_id;
 }

 @Column
 public String getSequence() {
  return sequence;
 }

 public void setSequence(String sequence) {
  this.sequence = sequence;
 }

}

To try query cache, we are going to implement one test where same query is executed multiple times.

@Autowired
private SessionFactory sessionFactory;

@Test
public void fiftyFirstDnaSequenceShouldBeReturnedAndCached() throws Exception {
 for (int i = 0; i < 5; i++) {
  Session session = sessionFactory.openSession();
  session.beginTransaction();

  Time elapsedTime = new Time("findDna"+i);

  List<Dna> list = session.createQuery(
    "from dna").setFirstResult(0).setMaxResults(50).setCacheable(true).list();


  session.getTransaction().commit();
  session.close();
  elapsedTime.miliseconds(System.out);

  for (Dna dna : list) {
   System.out.println(dna);
  }

 }
}

We can see that we are returning first fifty dna sequences, and if you execute it, you will see that elapsed time between creation of query and commiting transaction is printed. As you can suppose only first iteration takes about 5 seconds to get all data, but the other ones only milliseconds.

The foreach line just before query iteration will print object identifier through console. If you look carefully none of these identifiers will be repeated during all execution. This fact just goes to show you that Hibernate cache does not save objects but properties values, and the object itself is created each time.

Last note, remember that Hibernate does not cache associations by default.

Now after writing a query, think if it will contain static data and if it will be executed often. If it is the case, query cache is your friend to make Hibernate applications run faster.

Download Code

Reference: Hibernate cache levels tutorial from our JCG partner Alex Soto at the One Jar To Rule Them All blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

2 Responses to "Hibernate cache levels tutorial"

  1. I would like to ask something. Is it a good practice to make a “select * from a table” query cacheable? I mean, how will the cache knows for example if the application adds a new record to the table?

  2. Ravi Kumar says:

    can you give a example of Ehcache with jpa spring or Ehcache jpa only..i have tried with hibernate which is success but not able to do with JPA. thanks in advance..

Leave a Reply


− one = 7



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close