Hibernate框架中的缓存技术详解
本文实例讲述了hibernate框架中的缓存技术。分享给大家供大家参考,具体如下:
hibernate框架的缓存分为session的缓存、sessionfactory的缓存,也称为一级缓存和二级缓存。
一级缓存:
一级缓存是session级的缓存,其生命周期很短,与session相互对应,由hibernate进行管理,属于事务范围的缓存。当程序调用 session的load()方法、get()方法、save()方法、saveorupdate()方法、update()方法或查询接口方法时,hibernate会对实体对象进行缓存;当通过load()方法或get()方法查询实体对象时,hibernate会首先到缓存中查询,在找不到实体对像的情况下,hibernate才会发出sql语句到数据库中查询,从而提高了hibernate的使用效率。
举个例子来说吧:
package com.xqh.util; import org.hibernate.session; import com.xqh.model.user; public class test { public static void main(string[] args) { session session = null; try { session = hibernateutil.getsession(); // 获取session session.begintransaction(); //开启事务 system.out.println("第一次查询:"); user user = (user)session.get(user.class, new integer(1)); system.out.println("用户名:" + user.getname()); system.out.println("第二次查询:"); user user1 = (user)session.get(user.class, 1); system.out.println("用户名:" + user1.getname()); session.gettransaction().commit(); } catch (exception e) { e.printstacktrace(); // 出错将回滚事务 session.gettransaction().rollback(); } finally { // 关闭session对象 hibernateutil.closesession(session); } } }
当程序通过get()方法第一次查用户对象时,hibernate会发出一条sql语句进行查询,此时hibernate对其用户对象进行了一级缓存;当再次通过get()方法查询时,hibernate就不会发出sql语句了,因为用户名已经存在于一级缓存中。程序运行结果:
第一次查询: hibernate: select user0_.id as id0_0_, user0_.name as name0_0_, user0_.sex as sex0_0_ from tb_user_info user0_ where user0_.id=? 用户名:xqh 第二次查询: 用户名:xqh
注意:一级缓存的生命周期与session相对应,它并不会在session之间共享,在不同的session中不能得到其他session中缓存的实体对象
二级缓存:
二级缓存是sessionfactory级的缓存,其生命周期与sessionfactory一致。二级缓存可在多个session间共享,属于进程范围或群集范围的缓存。
二级缓存是一个可插拔的缓存插件,它的使用需要第三方缓存产品的支持。在hibernate框架中,通过hibernate配置文件配置二级缓存的使用策略。
1.加入缓存配置文件ehcache.xml
<ehcache> <!-- sets the path to the directory where cache .data files are created. if the path is a java system property it is replaced by its value in the running vm. the following properties are translated: user.home - user's home directory user.dir - user's current working directory java.io.tmpdir - default temp file path --> <diskstore path="java.io.tmpdir"/> <!--default cache configuration. these will applied to caches programmatically created through the cachemanager. the following attributes are required for defaultcache: maxinmemory - sets the maximum number of objects that will be created in memory eternal - sets whether elements are eternal. if eternal, timeouts are ignored and the element is never expired. timetoidleseconds - sets the time to idle for an element before it expires. is only used if the element is not eternal. idle time is now - last accessed time timetoliveseconds - sets the time to live for an element before it expires. is only used if the element is not eternal. ttl is now - creation time overflowtodisk - sets whether elements can overflow to disk when the in-memory cache has reached the maxinmemory limit. --> <defaultcache maxelementsinmemory="10000" eternal="false" timetoidleseconds="120" timetoliveseconds="120" overflowtodisk="true" /> <!--predefined caches. add your cache configuration settings here. if you do not have a configuration for your cache a warning will be issued when the cachemanager starts the following attributes are required for defaultcache: name - sets the name of the cache. this is used to identify the cache. it must be unique. maxinmemory - sets the maximum number of objects that will be created in memory eternal - sets whether elements are eternal. if eternal, timeouts are ignored and the element is never expired. timetoidleseconds - sets the time to idle for an element before it expires. is only used if the element is not eternal. idle time is now - last accessed time timetoliveseconds - sets the time to live for an element before it expires. is only used if the element is not eternal. ttl is now - creation time overflowtodisk - sets whether elements can overflow to disk when the in-memory cache has reached the maxinmemory limit. --> <!-- sample cache named samplecache1 this cache contains a maximum in memory of 10000 elements, and will expire an element if it is idle for more than 5 minutes and lives for more than 10 minutes. if there are more than 10000 elements it will overflow to the disk cache, which in this configuration will go to wherever java.io.tmp is defined on your system. on a standard linux system this will be /tmp" --> <cache name="samplecache1" maxelementsinmemory="10000" eternal="false" timetoidleseconds="300" timetoliveseconds="600" overflowtodisk="true" /> <!-- sample cache named samplecache2 this cache contains 1000 elements. elements will always be held in memory. they are not expired. --> <cache name="samplecache2" maxelementsinmemory="1000" eternal="true" timetoidleseconds="0" timetoliveseconds="0" overflowtodisk="false" /> --> <!-- place configuration for your caches following --> </ehcache>
2.设置hibernate配置文件。
<!-- 开启二级缓存 --> <property name="hibernate.cache.use_second_level_cache">true</property> <!-- 指定缓存产品提供商 --> <property name="hibernate.cache.provider_class">org.hibernate.cache.ehcacheprovider</property> <!-- 指定二级缓存应用到的实体对象 --> <class-cache class="com.xqh.model.user" usage="read-only"></class-cache>
例:
package com.xqh.util; import org.hibernate.session; import com.xqh.model.user; public class test { public static void main(string[] args) { session session = null; // 第一个session try { session = hibernateutil.getsession(); session.begintransaction(); system.out.println("第一次查询:"); user user = (user)session.get(user.class, 1); system.out.println("用户名:" + user.getname()); session.gettransaction().commit(); } catch (exception e) { e.printstacktrace(); // 出错将回滚事务 session.gettransaction().rollback(); } finally { // 关闭session对象 hibernateutil.closesession(session); } try { session = hibernateutil.getsession(); // 开启第二个缓存 session.begintransaction(); system.out.println("第二次查询:"); user user = (user)session.get(user.class, 1); system.out.println("用户名:" + user.getname()); session.gettransaction().commit(); } catch (exception e) { e.printstacktrace(); // 出错将回滚事务 session.gettransaction().rollback(); } finally { // 关闭session对象 hibernateutil.closesession(session); } } }
二级缓存在session之间是共享的,因此可在不同session中加载同一个对象,hibernate将只发出一条sql语句,当第二次加载对象时,hibernate将从缓存中获取此对象。
程序结果:
第一次查询: hibernate: select user0_.id as id0_0_, user0_.name as name0_0_, user0_.sex as sex0_0_ from tb_user_info user0_ where user0_.id=? 用户名:xqh 第二次查询: 用户名:xqh
对于二级缓存,可以使用一些不经常更新的数据或参考的数据,此时其性能会得到明显的提升。但如果经常变化的数据应用二级缓存,则性能方面会造成一定问题。
希望本文所述对大家基于hibernate框架的java程序设计有所帮助。
上一篇: ASP.NET下母版页和内容页中的事件发生顺序整理
下一篇: Java中字符编码格式详解
推荐阅读