转载:http://blog.csdn.net/chaoowang/article/details/21236501

hibernate使用版本是:hibernate-release-4.3.4.Final

需要的jar包:hibernate-release-4.3.4Final\lib\required下所有jar包

ehcache  jar包:hibernate-release-4.3.4.Final\lib\optional\ehcache下所有包

junit:junit-4.10.jar和mysql-connector-java-5.1.15-bin.jar

注:hibernate 4.2.5版本ehcache缓存不依赖commons-logging-1.1.1.jar,需要的是slf4j-api-1.6.1.jar

项目结构如下
 

hibernate.cfg.xml

  1. <?xml version='1.0' encoding='utf-8'?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5. <hibernate-configuration>
  6. <session-factory>
  7. <!-- Database connection settings -->
  8. <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  9. <property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernate4</property>
  10. <property name="connection.username">root</property>
  11. <property name="connection.password">root</property>
  12. <!-- JDBC connection pool (use the built-in) -->
  13. <property name="connection.pool_size">1</property>
  14. <!-- SQL dialect -->
  15. <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
  16. <!-- Enable Hibernate's automatic session context management -->
  17. <property name="current_session_context_class">thread</property>
  18. <!-- Disable the second-level cache -->
  19. <!--<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
  20. -->
  21. <!-- 配置二级缓存 -->
  22. <property name="hibernate.cache.use_second_level_cache">true</property>
  23. <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
  24. <!-- hibernate3的二级缓存配置 -->
  25. <!-- <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> -->
  26. <!-- 开启查询缓存 -->
  27. <property name="hibernate.cache.use_query_cache">true</property>
  28. <!-- Echo all executed SQL to stdout -->
  29. <property name="show_sql">true</property>
  30. <!-- Drop and re-create the database schema on startup -->
  31. <property name="hbm2ddl.auto">update</property>
  32. <mapping class="com.test.pojo.User" />
  33. </session-factory>
  34. </hibernate-configuration>

注意:hibernate4和hibernate3配置不一样,hibernate4是

  1. <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

而hibernate3的配置是

  1. <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

此处有一个疑问是:hibernate4的官方文档中,已经把class改了,但是属性名称没有改,还是
hibernate.cache.provider_class,不是上面的
hibernate.cache.region.factory_class,但是写成hibernate.cache.provider_class会
报下面错误

  1. org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.spi.CacheImplementor]
  2. at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:186)
  3. at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:150)
  4. at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
  5. at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:264)
  6. at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1790)
  7. at com.test.pojo.UserTest.beforeClass(UserTest.java:28)
  8. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  9. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  10. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  11. at java.lang.reflect.Method.invoke(Method.java:597)
  12. at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
  13. at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
  14. at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
  15. at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
  16. at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
  17. at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
  18. at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
  19. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
  20. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
  21. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
  22. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
  23. Caused by: org.hibernate.cache.NoCacheRegionFactoryAvailableException: Second-level cache is used in the application, but property hibernate.cache.region.factory_class is not given, please either disable second level cache or set correct region factory class name to property hibernate.cache.region.factory_class (and make sure the second level cache provider, hibernate-infinispan, for example, is available in the classpath).
  24. at org.hibernate.cache.internal.NoCachingRegionFactory.buildTimestampsRegion(NoCachingRegionFactory.java:87)
  25. at org.hibernate.cache.spi.UpdateTimestampsCache.<init>(UpdateTimestampsCache.java:62)
  26. at org.hibernate.internal.CacheImpl.<init>(CacheImpl.java:72)
  27. at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:40)
  28. at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:35)
  29. at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.initiateService(SessionFactoryServiceRegistryImpl.java:91)
  30. at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:176)
  31. ... 20 more

说是hibernate.cache.region.factory_class属性没有配置,估计官方文档里没有把属性改过来。。。

ehcache.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
  4. updateCheck="false">
  5. <!--
  6. name:cache唯一标识
  7. eternal:缓存是否永久有效
  8. maxElementsInMemory:内存中最大缓存对象数
  9. overflowToDisk(true,false):缓存对象达到最大数后,将缓存写到硬盘中
  10. diskPersistent:硬盘持久化
  11. timeToIdleSeconds:缓存清除时间
  12. timeToLiveSeconds:缓存存活时间
  13. memoryStoreEvictionPolicy:缓存清空策略
  14. 1.FIFO:first in first out 先讲先出
  15. 2.LFU: Less Frequently Used 一直以来最少被使用的
  16. 3.LRU:Least Recently Used  最近最少使用的
  17. -->
  18. <defaultCache maxElementsInMemory="1000" eternal="false"
  19. timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
  20. <cache name="userCache" eternal="false" maxElementsInMemory="1000"
  21. overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="3600"
  22. timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LFU" />
  23. </ehcache>

User实体类

  1. package com.test.pojo;
  2. import javax.persistence.Entity;
  3. import javax.persistence.GeneratedValue;
  4. import javax.persistence.GenerationType;
  5. import javax.persistence.Id;
  6. import org.hibernate.annotations.Cache;
  7. import org.hibernate.annotations.CacheConcurrencyStrategy;
  8. @Entity
  9. @Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
  10. public class User {
  11. @Id
  12. @GeneratedValue(strategy=GenerationType.IDENTITY)
  13. private int id;
  14. private String name;
  15. private int age;
  16. public int getId() {
  17. return id;
  18. }
  19. public void setId(int id) {
  20. this.id = id;
  21. }
  22. public String getName() {
  23. return name;
  24. }
  25. public void setName(String name) {
  26. this.name = name;
  27. }
  28. public int getAge() {
  29. return age;
  30. }
  31. public void setAge(int age) {
  32. this.age = age;
  33. }
  34. }

UserTest测试类:

  1. package com.test.pojo;
  2. import org.hibernate.HibernateException;
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.cfg.Configuration;
  6. import org.hibernate.service.ServiceRegistry;
  7. import org.hibernate.service.ServiceRegistryBuilder;
  8. import org.junit.BeforeClass;
  9. import org.junit.Test;
  10. public class UserTest {
  11. private static SessionFactory sessionFactory = null;
  12. @BeforeClass
  13. public static void beforeClass() {
  14. Configuration configuration = new Configuration();
  15. try {
  16. configuration.configure();
  17. } catch (HibernateException e) {
  18. // TODO Auto-generated catch block
  19. e.printStackTrace();
  20. }
  21. ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
  22. sessionFactory = configuration.buildSessionFactory(serviceRegistry);
  23. }
  24. @Test
  25. public void testEhcache() {
  26. Session session = sessionFactory.openSession();
  27. session.beginTransaction();
  28. User u1 = (User) session.load(User.class, 3);
  29. System.out.println(u1.getName());
  30. session.getTransaction().commit();
  31. session.close();
  32. Session session2 = sessionFactory.openSession();
  33. session2.beginTransaction();
  34. User u2 = (User) session2.load(User.class, 3);
  35. System.out.println(u2.getName());
  36. session2.getTransaction().commit();
  37. session2.close();
  38. }
  39. }

结果:

  1. Hibernate: select user0_.id as id1_0_0_, user0_.age as age2_0_0_, user0_.name as name3_0_0_ from User user0_ where user0_.id=?
  2. zhangsan
  3. zhangsan

list二级缓存测试

  1. package com.test.pojo;
  2. import java.util.List;
  3. import org.hibernate.HibernateException;
  4. import org.hibernate.Session;
  5. import org.hibernate.SessionFactory;
  6. import org.hibernate.cfg.Configuration;
  7. import org.hibernate.service.ServiceRegistry;
  8. import org.hibernate.service.ServiceRegistryBuilder;
  9. import org.junit.BeforeClass;
  10. import org.junit.Test;
  11. public class UserTest {
  12. private static SessionFactory sessionFactory = null;
  13. @BeforeClass
  14. public static void beforeClass() {
  15. Configuration configuration = new Configuration();
  16. try {
  17. configuration.configure();
  18. } catch (HibernateException e) {
  19. // TODO Auto-generated catch block
  20. e.printStackTrace();
  21. }
  22. ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
  23. sessionFactory = configuration.buildSessionFactory(serviceRegistry);
  24. }
  25. @SuppressWarnings("unchecked")
  26. @Test
  27. public void testListEhcache() {
  28. Session session = sessionFactory.openSession();
  29. session.beginTransaction();
  30. List<User> users1 = (List<User>)session.createQuery("from User").setCacheable(true).list();
  31. for(User user : users1) {
  32. System.out.println(user.getName());
  33. }
  34. session.getTransaction().commit();
  35. session.close();
  36. Session session2 = sessionFactory.openSession();
  37. session2.beginTransaction();
  38. List<User> users2 = (List<User>)session2.createQuery("from User").setCacheable(true).list();
  39. for(User user : users2) {
  40. System.out.println(user.getName());
  41. }
  42. session2.getTransaction().commit();
  43. session2.close();
  44. }
  45. }

输出结果:

  1. Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from User user0_
  2. zhangsan
  3. zhangsan
  4. lisi
  5. wangwu
  6. zhangsan
  7. zhangsan
  8. lisi
  9. wangwu

hibernate4 二级缓存demo实例的更多相关文章

  1. MyBatis从入门到放弃六:延迟加载、一级缓存、二级缓存

    前言 使用ORM框架我们更多的是使用其查询功能,那么查询海量数据则又离不开性能,那么这篇中我们就看下mybatis高级应用之延迟加载.一级缓存.二级缓存.使用时需要注意延迟加载必须使用resultMa ...

  2. Hibernate一级缓存、二级缓存以及查询缓存的关系

    转载自http://blog.csdn.net/maoyeqiu/article/details/50209893 前两天总结了一下二级缓存和查询缓存的关系,但是又有一个新的问题,就是查询缓存缓存到二 ...

  3. ssh整合hibernate 使用spring管理hibernate二级缓存,配置hibernate4.0以上二级缓存

    ssh整合hibernate 使用spring管理hibernate二级缓存,配置hibernate4.0以上二级缓存 hibernate  : Hibernate是一个持久层框架,经常访问物理数据库 ...

  4. Hibernate4教程六:性能提升和二级缓存

    抓取策略(fetching strategy)是指:当应用程序需要在(Hibernate实体对象图的)关联关系间进行导航的时候,Hibernate如何获取关联对象的策略.抓取策略可以在O/R映射的元数 ...

  5. Hibernate4.1.4配置二级缓存EHCache步骤

    1.当然首先引入EHCache相关的jar包 这些包不需要另外下载,在Hibernate官方网站下载Hibernate4.1.7的压缩包(如:hibernate-release-4.1.7.Final ...

  6. Hibernate4+EhCache配置二级缓存

    本文主要讲一讲Hibernate+EhCache配置二级缓存的基本使用方法 (有关EhCache的基础介绍可参见:http://sjsky.iteye.com/blog/1288257 ) Cache ...

  7. Spring源码-IOC部分-循环依赖-用实例证明去掉二级缓存会出现什么问题【7】

    实验环境:spring-framework-5.0.2.jdk8.gradle4.3.1 Spring源码-IOC部分-容器简介[1] Spring源码-IOC部分-容器初始化过程[2] Spring ...

  8. Spring 整合 Hibernate 时启用二级缓存实例详解

    写在前面: 1. 本例使用 Hibernate3 + Spring3: 2. 本例的查询使用了 HibernateTemplate: 1. 导入 ehcache-x.x.x.jar 包: 2. 在 a ...

  9. Hibernate笔记④--一级二级缓存、N+1问题、saveorupdate、实例代码

    一级缓存及二级缓存 一级缓存也是Session 缓存     一个链接用户的多次查询使用缓存     跨用户 则无缓存     hibernate自带的 get和load都会填充并利用一级缓存 二级缓 ...

随机推荐

  1. DB2 的create or update方法

    通过merge方法实现的: MERGE INTO IFEBASE.STYLE AS MT USING (SELECT :scenario AS SCENARIO_ID, :style AS SHAPE ...

  2. 强大的grep命令

    1.作用 Linux系统中grep命令是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹 配的行打印出来.grep全称是Global Regular Expression Print,表示全 ...

  3. Javascript 正则表达式笔记2

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...

  4. (12)nehe教程6 纹理映射

    在这一课里,我将教会你如何把纹理映射到立方体的六个面. 学习 texture map 纹理映射(贴图)有很多好处.比方说您想让一颗导弹飞过屏幕.根据前几课的知识,我们最可行的办法可能是很多个多边形来构 ...

  5. Android Grapics图像类体系

  6. UVA 11361 - Investigating Div-Sum Property 数位DP

    An integer is divisible by 3 if the sum of its digits is also divisible by 3. For example, 3702 is d ...

  7. 理解 JMeter 聚合报告(Aggregate Report)

    Aggregate Report 是 JMeter 常用的一个 Listener,中文被翻译为“聚合报告”.今天再次有同行问到这个报告中的各项数据表示什么意思,顺便在这里公布一下,以备大家查阅. 如果 ...

  8. 2016CVTE编程题:兔子藏洞

    兔子藏洞 题目描述 一只兔子藏身于20个圆形排列的洞中(洞从1开始编号),一只狼从x号洞开始找,下次隔一个洞找(及在x+2号洞找),在下次个两个洞找(及在x+5号洞找),以此类推...它找了n次仍然没 ...

  9. 【Apache运维基础(4)】Apache的Rewrite攻略(1)

    简述 Rewirte主要的功能就是实现URL的跳转,它的正则表达式是基于Perl语言.可基于服务器级的(httpd.conf)和目录级的 (.htaccess)两种方式.如果要想用到rewrite模块 ...

  10. 负载均衡之Haproxy配置详解(及httpd配置)

    下图描述了使用keepalived+Haproxy主从配置来达到能够针对前段流量进行负载均衡到多台后端web1.web2.web3.img1.img2.但是由于haproxy会存在单点故障问题,因此使 ...