1. 在hibernate.fcg.xml配置文件中开启二级缓存:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property><property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property><property name="connection.username">oa</property><property name="connection.password">oa</property><property name="connection.pool_size">1</property><!-- SQL dialect --><property name="dialect">org.hibernate.dialect.Oracle10gDialect</property><property name="show_sql">true</property><property name="format_sql">true</property><property name="hbm2ddl.auto">update</property><!-- 开启二级缓存 --><property name="hibernate.cache.use_second_level_cache">true</property><!-- 设置二级缓存的实现类 --><property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property><!-- Hibernate4以后都封装到org.hibernate.cache.ehcache.EhCacheRegionFactory --><property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property><!-- 指定缓存配置文件位置 --><property name="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</property><!--启动查询缓存,如果想缓存使用findAll、list、iterator、createCriteria、createQuery等方法获得的数据结果集,必须配置此项--><property name="hibernate.cache.use_second_level_cache">true</property><mapping resource="com/huey/entity/mapping/Person.hbm.xml" /></session-factory></hibernate-configuration>

2. 导入二级缓存所需的jar包。以EHCache为例,需导入Hibernate项目路径下的lib\optional\ehcache中的jar包,同时EHCache还依赖于commons-logging和backport-util-concurrent这两个jar包。

3. 对于EHCache缓存,它还需要一个ehcache.xml配置文件:

<?xml version="1.0"?>
<ehcache><diskStore path="java.io.tmpdir"/><defaultCachemaxElementsInMemory="10000"eternal="false"overflowToDisk="true"timeToIdleSeconds="120"timeToLiveSeconds="120"diskPersistent="false"/>
</ehcache>

配置文件中属性的说明:

maxElementsInMemory:设置缓存中最多可放入多少个对象;
eternal:设置缓存是否永久有效;
overflowToDisk:设置当内存中缓存的记录达到maxElementsInMemory时是否被持久化到硬盘中,保存路径由<diskStore.../>元素指定。
timeToIdleSeconds:设置缓存的对象多少秒没有被使用就会被清理掉;
timeToLiveSeconds:设置缓存的对象在过期之前可以缓存多少秒;
diskPersistent:设置在虚拟机重启时是否进行磁盘存储。

4. 设置对哪些实体类、实体的哪些集合属性启用二级缓存。有两种方式:

1) 在持久化映射文件的<class .../>元素或<set.../>、<list .../>等集合元素内使用<cache .../>元素指定缓存策略。

2) 在hibernate.cfg.xml文件中使用<class-cache .../>或<collection-cache .../>元素对指定的持久化类、集合属性启用二级缓存。

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="com.huey.entity"><class name="Person" table="tab_person"><!-- 指定持久化类Person开启二级缓存,并指定缓存策略为只读策略 --><cache usage="read-only"/><id name="id" column="id"><generator class="sequence"><param name="sequence">PERSON_ID_SEQUENCE</param></generator></id><property name="name" column="name" /><property name="gender" column="gender"/><property name="birthday" column="birthday"/></class>
</hibernate-mapping>

5. 测试用例:

package com.huey.test;import java.util.List;import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.Test;import com.huey.entity.Person;public class PersonTest {private static SessionFactory sf;static {Configuration configuration = new Configuration().configure("hibernate.cfg.xml");ServiceRegistryBuilder srb = new ServiceRegistryBuilder().applySettings(configuration.getProperties());sf = configuration.buildSessionFactory(srb.buildServiceRegistry());}@Testpublic void testPerson() throws Exception {Session session = sf.openSession();session.beginTransaction(); List<?> people = session.createQuery("from Person").list();for (Object object : people) {Person person = (Person)object;System.out.println(person.getName());}session.getTransaction().commit();session.close();Session session2 = sf.openSession();session2.beginTransaction(); Person person = (Person)session2.get(Person.class, 1);System.out.println(person.getName());session2.getTransaction().commit();session2.close();}
}

可以发现,启用二级缓存后,即使session关闭之后,第二个查询仍不需发送SQL查询语句。

Hibernate二级缓存的简单示例相关推荐

  1. hibernate二级缓存(三) 自定义实现一个简单的hibernate二级缓存

    hibernate二级缓存(三) 自定义实现一个简单的hibernate二级缓存 前面我们已经提及过hibernate内部为二级缓存的扩展做了很多的实现.我们只需要实现RegionFactoryTem ...

  2. Hibernate EHCache - Hibernate二级缓存

    Hibernate EHCache - Hibernate二级缓存 欢迎使用Hibernate二级缓存示例教程.今天我们将研究Hibernate EHCache,它是最受欢迎的Hibernate二级缓 ...

  3. HibernateEHCache –Hibernate二级缓存

    Welcome to the Hibernate Second Level Cache Example Tutorial. Today we will look into Hibernate EHCa ...

  4. spring boot集成ehcache 2.x 用于hibernate二级缓存

    spring boot集成ehcache 2x 用于hibernate二级缓存 项目依赖 Ehcache简介 hibernate二级缓存配置 ehcache配置文件 ehcache事件监听 注解方式使 ...

  5. Hibernate二级缓存问题

    相关概念和定义 1.缓存的意义 把一些不常修改,但是又经常用的数据存放到内存中,这样能减少与数据库的交互,提升程序的性能 2.Hibernate中提供了两级缓存: 第一级别的缓存是Session级别的 ...

  6. spring boot 2.1.4 hibernate二级缓存 Hazelcast实现(一)

    Hazelcast优势网上都可以查到,默认的分布式缓存,使用Hazelcast替换ehcache优势比较明显,也方便项目从单机到发展分布式,而不用再引入其他组件也达到了性能要求,按照springboo ...

  7. Hibernate二级缓存详解(转)

    Hibernate二级缓存详解(转) 本文转载 http://www.blogjava.net/supercrsky/articles/238580.html 与Session相对的是,Session ...

  8. Hibernate二级缓存攻略

    Hibernate二级缓存攻略 很多人对二级缓存都不太了解,或者是有错误的认识,我一直想写一篇文章介绍一下hibernate的二级缓存的,今天终于忍不住了. fi9-DVR]   我的经验主要来自hi ...

  9. Hibernate二级缓存的使用

    1启用Hibernate二级缓存 Hibernate二级缓存分为两部分,class缓存和查询缓存,其获取对象的方式有所不同,但两者也有联系,查询缓存必须以class缓存为基础才能起作用,否则只会使效率 ...

最新文章

  1. 全球最大的3D数据集公开了!标记好的10800张全景图
  2. 如何访问云端的tcpserver_远程读写FTP文件,花生壳盒子+Serv-U快速实现远程访问...
  3. JAVA基础知识|lambda与stream
  4. RxPermissions 源码解析之举一反三
  5. 汇编语言转为c语言,如何把汇编语言转换成C语言
  6. php 兼容unicode文字的字符串大小写转换,php实现兼容Unicode文字的字符串大小写转换strtolower()和strtoupper()...
  7. L - All in All(子序列)
  8. Oracle EBS-SQL (PO-5):采购订单控制信息查询.sql
  9. 关于C++ const成员的一些细节
  10. 盘点一款手机Python编程神器——AidLearning
  11. OD查找QQ sessionkey教程
  12. CSS揭破实用窍门总结
  13. PHP 第三方调用 UC_Center用户登录认证
  14. win7触摸板怎么关闭_笔记本连接鼠标后自动关闭触摸板功能的方法
  15. 前端效果之“拉开窗帘”
  16. Linux云计算运维之Shell
  17. 你不知道的nodejs性能优化
  18. Memory Analyzer Tool 1 Shallow heap Retained heap dominator tree(控制树)
  19. Android APP开发框架选择——JSBridge既个人心得和技巧
  20. 百度,你是神一样的搜索引擎

热门文章

  1. 改变UItoolbar的背景色
  2. Solr or Lucene全文检索实现原理
  3. Ajax 查询手机号码归属地
  4. 017 | 精准扶贫视野下非遗传承的研究与启示——以三峡皮影为例 | 大学生创新训练项目申请书 | 极致技术工厂
  5. SVN之下载项目一半下载中断了转圈圈无响应解决办法cleanup failed to process the following path
  6. jsp+ssm+springboot校园旧书交易交换平台java项目
  7. c++实现自动查找qq号并发送消息
  8. 7-4 大众情人(Floyd)
  9. 芜湖职业技术学院大专计算机应用各科分数,安徽计算机对口高考分数线
  10. 苹果最新系统ios7_拳皇97 Mac版 苹果电脑 Mac游戏 支持最新系统