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.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

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


seven − 5 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
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.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books