hibernate4 二级缓存demo实例
转载: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
- <?xml version='1.0' encoding='utf-8'?>
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <!-- Database connection settings -->
- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
- <property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernate4</property>
- <property name="connection.username">root</property>
- <property name="connection.password">root</property>
- <!-- JDBC connection pool (use the built-in) -->
- <property name="connection.pool_size">1</property>
- <!-- SQL dialect -->
- <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
- <!-- Enable Hibernate's automatic session context management -->
- <property name="current_session_context_class">thread</property>
- <!-- Disable the second-level cache -->
- <!--<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
- -->
- <!-- 配置二级缓存 -->
- <property name="hibernate.cache.use_second_level_cache">true</property>
- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
- <!-- hibernate3的二级缓存配置 -->
- <!-- <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> -->
- <!-- 开启查询缓存 -->
- <property name="hibernate.cache.use_query_cache">true</property>
- <!-- Echo all executed SQL to stdout -->
- <property name="show_sql">true</property>
- <!-- Drop and re-create the database schema on startup -->
- <property name="hbm2ddl.auto">update</property>
- <mapping class="com.test.pojo.User" />
- </session-factory>
- </hibernate-configuration>
注意:hibernate4和hibernate3配置不一样,hibernate4是
- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
而hibernate3的配置是
- <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会
报下面错误
- org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.spi.CacheImplementor]
- at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:186)
- at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:150)
- at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
- at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:264)
- at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1790)
- at com.test.pojo.UserTest.beforeClass(UserTest.java:28)
- at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
- at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
- at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
- at java.lang.reflect.Method.invoke(Method.java:597)
- at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
- at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
- at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
- at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
- at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
- at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
- at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
- at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
- at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
- at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
- at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
- 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).
- at org.hibernate.cache.internal.NoCachingRegionFactory.buildTimestampsRegion(NoCachingRegionFactory.java:87)
- at org.hibernate.cache.spi.UpdateTimestampsCache.<init>(UpdateTimestampsCache.java:62)
- at org.hibernate.internal.CacheImpl.<init>(CacheImpl.java:72)
- at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:40)
- at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:35)
- at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.initiateService(SessionFactoryServiceRegistryImpl.java:91)
- at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:176)
- ... 20 more
说是hibernate.cache.region.factory_class属性没有配置,估计官方文档里没有把属性改过来。。。
ehcache.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
- updateCheck="false">
- <!--
- name:cache唯一标识
- eternal:缓存是否永久有效
- maxElementsInMemory:内存中最大缓存对象数
- overflowToDisk(true,false):缓存对象达到最大数后,将缓存写到硬盘中
- diskPersistent:硬盘持久化
- timeToIdleSeconds:缓存清除时间
- timeToLiveSeconds:缓存存活时间
- memoryStoreEvictionPolicy:缓存清空策略
- 1.FIFO:first in first out 先讲先出
- 2.LFU: Less Frequently Used 一直以来最少被使用的
- 3.LRU:Least Recently Used 最近最少使用的
- -->
- <defaultCache maxElementsInMemory="1000" eternal="false"
- timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
- <cache name="userCache" eternal="false" maxElementsInMemory="1000"
- overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="3600"
- timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LFU" />
- </ehcache>
User实体类
- package com.test.pojo;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.GenerationType;
- import javax.persistence.Id;
- import org.hibernate.annotations.Cache;
- import org.hibernate.annotations.CacheConcurrencyStrategy;
- @Entity
- @Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
- public class User {
- @Id
- @GeneratedValue(strategy=GenerationType.IDENTITY)
- private int id;
- private String name;
- private int age;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
UserTest测试类:
- package com.test.pojo;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import org.hibernate.service.ServiceRegistry;
- import org.hibernate.service.ServiceRegistryBuilder;
- import org.junit.BeforeClass;
- import org.junit.Test;
- public class UserTest {
- private static SessionFactory sessionFactory = null;
- @BeforeClass
- public static void beforeClass() {
- Configuration configuration = new Configuration();
- try {
- configuration.configure();
- } catch (HibernateException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
- sessionFactory = configuration.buildSessionFactory(serviceRegistry);
- }
- @Test
- public void testEhcache() {
- Session session = sessionFactory.openSession();
- session.beginTransaction();
- User u1 = (User) session.load(User.class, 3);
- System.out.println(u1.getName());
- session.getTransaction().commit();
- session.close();
- Session session2 = sessionFactory.openSession();
- session2.beginTransaction();
- User u2 = (User) session2.load(User.class, 3);
- System.out.println(u2.getName());
- session2.getTransaction().commit();
- session2.close();
- }
- }
结果:
- 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=?
- zhangsan
- zhangsan
list二级缓存测试
- package com.test.pojo;
- import java.util.List;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import org.hibernate.service.ServiceRegistry;
- import org.hibernate.service.ServiceRegistryBuilder;
- import org.junit.BeforeClass;
- import org.junit.Test;
- public class UserTest {
- private static SessionFactory sessionFactory = null;
- @BeforeClass
- public static void beforeClass() {
- Configuration configuration = new Configuration();
- try {
- configuration.configure();
- } catch (HibernateException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
- sessionFactory = configuration.buildSessionFactory(serviceRegistry);
- }
- @SuppressWarnings("unchecked")
- @Test
- public void testListEhcache() {
- Session session = sessionFactory.openSession();
- session.beginTransaction();
- List<User> users1 = (List<User>)session.createQuery("from User").setCacheable(true).list();
- for(User user : users1) {
- System.out.println(user.getName());
- }
- session.getTransaction().commit();
- session.close();
- Session session2 = sessionFactory.openSession();
- session2.beginTransaction();
- List<User> users2 = (List<User>)session2.createQuery("from User").setCacheable(true).list();
- for(User user : users2) {
- System.out.println(user.getName());
- }
- session2.getTransaction().commit();
- session2.close();
- }
- }
输出结果:
- Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from User user0_
- zhangsan
- zhangsan
- lisi
- wangwu
- zhangsan
- zhangsan
- lisi
- wangwu
hibernate4 二级缓存demo实例的更多相关文章
- MyBatis从入门到放弃六:延迟加载、一级缓存、二级缓存
前言 使用ORM框架我们更多的是使用其查询功能,那么查询海量数据则又离不开性能,那么这篇中我们就看下mybatis高级应用之延迟加载.一级缓存.二级缓存.使用时需要注意延迟加载必须使用resultMa ...
- Hibernate一级缓存、二级缓存以及查询缓存的关系
转载自http://blog.csdn.net/maoyeqiu/article/details/50209893 前两天总结了一下二级缓存和查询缓存的关系,但是又有一个新的问题,就是查询缓存缓存到二 ...
- ssh整合hibernate 使用spring管理hibernate二级缓存,配置hibernate4.0以上二级缓存
ssh整合hibernate 使用spring管理hibernate二级缓存,配置hibernate4.0以上二级缓存 hibernate : Hibernate是一个持久层框架,经常访问物理数据库 ...
- Hibernate4教程六:性能提升和二级缓存
抓取策略(fetching strategy)是指:当应用程序需要在(Hibernate实体对象图的)关联关系间进行导航的时候,Hibernate如何获取关联对象的策略.抓取策略可以在O/R映射的元数 ...
- Hibernate4.1.4配置二级缓存EHCache步骤
1.当然首先引入EHCache相关的jar包 这些包不需要另外下载,在Hibernate官方网站下载Hibernate4.1.7的压缩包(如:hibernate-release-4.1.7.Final ...
- Hibernate4+EhCache配置二级缓存
本文主要讲一讲Hibernate+EhCache配置二级缓存的基本使用方法 (有关EhCache的基础介绍可参见:http://sjsky.iteye.com/blog/1288257 ) Cache ...
- Spring源码-IOC部分-循环依赖-用实例证明去掉二级缓存会出现什么问题【7】
实验环境:spring-framework-5.0.2.jdk8.gradle4.3.1 Spring源码-IOC部分-容器简介[1] Spring源码-IOC部分-容器初始化过程[2] Spring ...
- Spring 整合 Hibernate 时启用二级缓存实例详解
写在前面: 1. 本例使用 Hibernate3 + Spring3: 2. 本例的查询使用了 HibernateTemplate: 1. 导入 ehcache-x.x.x.jar 包: 2. 在 a ...
- Hibernate笔记④--一级二级缓存、N+1问题、saveorupdate、实例代码
一级缓存及二级缓存 一级缓存也是Session 缓存 一个链接用户的多次查询使用缓存 跨用户 则无缓存 hibernate自带的 get和load都会填充并利用一级缓存 二级缓 ...
随机推荐
- (转)Engineering Productivity
(转)http://www.wandoujia.com/blog/from-qa-to-ep 这个文章之前读过,很不错.今天再读,有不一样的感受!推荐下. 下面是几段摘录: EP 是什么 说到这里,E ...
- 关于WSDL
Message Operation 最核心的在于Operation 只要关心Operation就可以了,Operation只有Input, Output没有其他内容,是相对固定的.只要关心一下Inpu ...
- Shell 备忘录
此文收集工作中用到的Shell备忘,随用随机: 1.比较 -eq 等于,如:if [ "$a" -eq "$b" ] -ne 不等于,如 ...
- DevSecOps 简介(一)
DevOps,或者说企业应用开发团队和系统运营团队的合作,已经成为一个时髦的 IT 话题.这一新的运营模式往往与敏捷式软件开发方法并举,同时还会利用云计算的可扩展性--这一切,都是为了使企业更加灵活, ...
- 一道有趣的javascript编程题
题目:实现以下功能 1. 点击按钮“打开新窗口”,打开新的子页面,要求新窗口的大小为400px X 200px 2. 输入地址信息,点击“确定”按钮,关闭该页面 3. 将子页面中输入的地址信息,回传到 ...
- (转)单机上配置hadoop
哈哈,几天连续收到百度两次电话,均是利好消息,于是乎不知不觉的自己的工作效率也提高了,几天折腾了好久终于在单机上配置好了hadoop,然后也成功的运行了一个用例,耶耶耶耶耶耶. 转自:http://w ...
- HDU 2126 Buy the souvenirs (01背包,输出方案数)
题意:给出t组数据 每组数据给出n和m,n代表商品个数,m代表你所拥有的钱,然后给出n个商品的价值 问你所能买到的最大件数,和对应的方案数.思路: 如果将物品的价格看做容量,将它的件数1看做价值的话, ...
- 2014多校第六场 1005 || HDU 4925 Apple Tree
题目链接 题意 : 给你一块n×m的矩阵,每一个格子可以施肥或者是种苹果,种一颗苹果可以得到一个苹果,但是如果你在一个格子上施了肥,那么所有与该格子相邻(指上下左右)的有苹果树的地方最后得到的苹果是两 ...
- sql 泡沫 或者 递归查询
if object_id('[tb]') is not null drop table [tb] go ),parentid int) insert [tb] ,N union all ,N unio ...
- C#日期大全
DateTime dt = DateTime.Now; // Label1.Text = dt.ToString();//2005-11-5 13:21:25 // Label2.Text = dt. ...