Understanding Caching in Hibernate – Part Three : The Second Level Cache
来源:互联网 发布:java spring mvc路由 编辑:程序博客网 时间:2024/05/20 16:42
In the last posts I already covered the session cache as well as the query cache. In this post I will focus on the second-level cache. The Hibernate Documentation provides a good entry point reading on the second-level cache.
The key characteristic of the second-level cache is that is is used across sessions, which also differentiates it from the session cache, which only – as the name says – has session scope. Hibernate provides a flexible concept to exchange cache providers for the second-level cache. By default Ehcache is used as caching provider. However more sophisticated caching implementation can be used like the distributedJBoss Cache orOracle Coherence.
First we have to modify our code sample so that we now load the Person object in two sessions. The source code then looks as follows
public void loadInTwoSessions (){ // loading in first session Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); Person p = (Person) session.load(Person.class, 1L); System.out.println(p.getFirstName()); tx.commit(); session.close(); // loading in second session session = getSessionFactory().openSession(); tx = session.beginTransaction(); p = (Person) session.load(Person.class, 1L); System.out.println(p.getFirstName()); tx.commit(); session.close(); }
As we have not activated the second level cache, we expect the SQL queries to be executed twice. Looking at the PurePath of this transactions verifies our asumption.
Now we activate the second-level cache. Activating the second level cache requires us change to Hibernate configuration file and enable second-level caching by adding and additionally specify the cache provider as shown below.
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
In this example I am using Ehcache for demonstration purposes. In order to enable caching of our Person objects if have to specify the caching configuration in the ehcache.xml file. The actual cache configuration depends on the caching provider. For Ehcache the configuartion is defined as follows. The configuration for the Person class used in the example is boiler-plate Ehcache configuration. It can be adopted to specific needs. Describing all possible configurations options like using mulitple cache regions etc. is beyond scope of this post.
<cache name="com.dynatrace.samples.database.Person" maxElementsInMemory="300" eternal="true" overflowToDisk="false" timeToIdleSeconds="12000" timeToLiveSeconds="12000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />
Finally we have to configure caching also at Hibernate level. Hibernate supports mulitple settings for caching. As we are only reading data it the moment a read-only cache is sufficient for our purposes. Hibernate for sure supports read-write cache as well and also transactional caches in case this is supported by the cache provider. The following liine in the hibernate configuration enable read-only caching forPerson objects. Alternatively also Hibernate associations could be used.
<cache usage=”read-only” />
Now we expect the object to be retrieved from the second-level the second time it is loaded. A PurePath trace verifies this assumption. Now, only the first time a database call gets executed.
Read-Write Caching
After having looked at plain read caching we look in the next step at read-write caching. Our code example gets a bit more complex. We again use two sessions. We load the object in the first session, update it thenload it in the second session. Both sessions are created upfront and are kept open until the end.
public void complexLoad (){ Session session1 = getSessionFactory().openSession(); Session session2 = getSessionFactory().openSession(); Transaction tx1 = session1.beginTransaction(); Person p1 = (Person) session1.load(Person.class, 1L); System.out.println (p1.getFirstName()); p1.setFirstName ("" + System.currentTimeMillis()); tx1.commit(); Transaction tx2 = session2.beginTransaction(); Person p2 = (Person)session2.load(Person.class, 1L); System.out.println (p2.getFirstName()); tx2.commit(); session1.close(); session2.close();}
We expect the object to be retrieved from the cache when it is loaded in the second session. Looking at the PurePath of this transaction however shows something different. This method executes three SQL statements. First a SELECT to load the Person object, then an UPDATE to update the record in the database and then again a SELECT to load the Person object for the second session.
This is not what we necessarily where expecting. The object could have been retrieved from the cache in the second session. However it got loaded from the database. So why wasn’t the object taken from the cache. A closer look at the internal Hibernate behaviour unveils this secret.
The PurePath snippet above shows the details for loading the Person object in the second session. The key is theisGettable method, which in this case returns false. The input to isGettableis the session creation timestamp, as indicated by the arrow. A look at the sourcecode unveils what is checked within this method.
public boolean isGettable(long txTimestamp) { return freshTimestamp < txTimestamp;}
The method verifies wheter the session’s timestamp (txTimestamp) is greated than thefreshTimestamp of the cached object. In our case the second session was created BEFORE the object was updated. Consequently this method will return false. If we modify our code as follows the object will be loaded from the second-level cache.
public void complexLoad (){ Session session1 = getSessionFactory().openSession(); Transaction tx1 = session1.beginTransaction(); Person p1 = (Person) session1.load(Person.class, 1L); System.out.println (p1.getFirstName()); p1.setFirstName ("" + System.currentTimeMillis()); tx1.commit(); Session session2 = getSessionFactory().openSession(); Transaction tx2 = session2.beginTransaction(); Person p2 = (Person)session2.load(Person.class, 1L); System.out.println (p2.getFirstName()); tx2.commit(); session1.close(); session2.close();}
The PurePath snipped below verfies this assumption and shows that this time isGettable returns true and the object is retrieved from the cache.
Interaction of Session and Second-Level Cache
Finally I want to take a short look of the interaction between the session and the second-level cache. The important point to understand is that as soon as we use the second-level cache we have two caches in place. Caches are always a source of inconsistent information, which we take as the price for better performance and scalability. In order to avoid problems and unwanted behaviour we have to understand their internal behaviour. Hibernate always tries to first retrieve objects from the session and if this fails tries to retrieve them from the second-level cache. If this fails again objects are directly loaded from the database. The PurePath snippet below shows this loading behavior.
Conclusion
The second level cache is powerful mechanism for improving performance and scalability of your database driven application. Read-only caches are easy to handle, while read-write caches are more subtile in their behavior. Especially the interaction with the Hibernate session can lead to unwanted behavior. Sessions should therefore be used as what they are designed for – a transactional context. There are more details on the second-level cache I did not elaborate on like synchronization or replication behavior. However the combination of the three caching articles should provide good insight into Hibernate caching behavior.
If you’re interested in getting a better idea of how dynaTrace provides this transactional context (PurePath), you cancheck out this 14 minute video I contributed to which gets into some of the details of the product.
转自:http://apmblog.compuware.com/2009/03/24/understanding-caching-in-hibernate-part-three-the-second-level-cache/
- Understanding Caching in Hibernate – Part Three : The Second Level Cache
- Understanding Caching in Hibernate – Part Two : The Query Cache
- Understanding Caching in Hibernate – Part One : The Session Cache
- The Second Level Cache
- Hibernate 4 Second Level Caching With EHCache
- 探索 Hibernate 3.3 second-level cache
- Using Second Level Caching in a JPA Application
- Understanding hibernate first level cache with example
- org.hibernate.cache.NoCachingEnabledException: Second-level cache is not enabled
- Understanding Caching(深入理解cache)
- Understanding Caching(深入理解cache)
- Understanding Caching(深入理解cache)
- 配置Spring+hibernate使用ehcache作为second-level cache
- 配置Spring+hibernate使用ehcache作为second-level cache
- Hibernate 一级缓存(First-level cache)和二级缓存(second-level cache) 介绍
- Speed Up Your Hibernate Applications with Second-Level Caching (with Ehcache example)
- Hibernate second level cach
- Hibernate second level cach
- Android中使用SoftReference缓存图片对象
- C++ACE实现通用的服务器C/S架构通信程序
- 类成员函数作为CallBack函数时3种访问类成员变量的方法
- php中流的访问
- 控制HTML Input只能输入数字和小数点
- Understanding Caching in Hibernate – Part Three : The Second Level Cache
- DB2函数
- 数据结构的选择
- iOS多线程编程指南(一)关于多线程编程
- PHP 破解加密
- 求数组中最长递增子序列
- 3.opencv之画图1
- 国际化软件测试内容解析
- 无法找到服务器应用程序,源文件,和项目或返回的未知错误。请重新安装服务程序