`
dreamoftch
  • 浏览: 493105 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

hibernate缓存ehcache用法

阅读更多

 

一级缓存:session级别

 

二级缓存:sessionFactory级别

 

查询缓存:相同的SQL语句,不再重复执行

 

 

默认情况下,hibernate已经支持一级缓存了。

 

要支持二级缓存,步骤如下:

 

 在spring配置文件applicationContext.xml中加入下面配置:

 

 

 

	<!-- cache manager -->
	<bean id="cacheManager"
		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		<property name="shared" value="true" />
		<property name="configLocation" value="classpath:ehcache.xml" />
	</bean>
	<bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
		<property name="cacheManager" ref="cacheManager" />
		<property name="cacheName" value="root" />
	</bean>

 

 

同时需要在hibernate的配置文件hibernate.cfg.xml中添加下面配置(下面包括了查询缓存和二级缓存):

 

 

		<!-- use query cache -->
		<property name="hibernate.cache.use_query_cache">true</property>
                <!-- user second level cache -->
		<property name="hibernate.cache.use_second_level_cache">true</property>
		<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

 

 

以及ehcache.xml(ehcache自身的配置文件):

 

 

<?xml version="1.0" encoding="UTF-8" ?>
<ehcache>

	<diskStore path="java.io.tmpdir"/>
	
	<defaultCache 
        eternal="false"
        timeToIdleSeconds="1200"
        timeToLiveSeconds="3600"
		maxElementsInMemory="10000" 
		overflowToDisk="true">
	</defaultCache>
	
	<cache   
        name="org.hibernate.cache.StandardQueryCache"    
        maxElementsInMemory="50"
        eternal="false"
        timeToIdleSeconds="3600"
        timeToLiveSeconds="7200"
        overflowToDisk="false"
    />   
  
    <cache   
        name="org.hibernate.cache.UpdateTimestampsCache"
        maxElementsInMemory="5000"
        eternal="false"
        timeToIdleSeconds="3600"
        timeToLiveSeconds="7200"
        overflowToDisk="false"
    />
</ehcache>

 

 

另外,假如我们需要对User这个类进行缓存,需要加下面注解:@cache      ,如果映射方式是通过xml的方式的话,需要用另外的方式,这里就不多说了

 

 

package com.tch.test.ssh.entity.annotation;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;


/**
 * User entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name="user")
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class User implements java.io.Serializable {

	// Fields


	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Integer id;
	private String name;
	private String password;
	//private Set<Priority> priorities;

	// Constructors

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password
				 + "]";
	}

	/** default constructor */
	public User() {
	}

	/** full constructor */
	public User(String name, String password) {
		this.name = name;
		this.password = password;
	}

	// Property accessors

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}


	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

 

 

然后就可以使用了:

假如我们页面有个地方,多次调用了Dao层的一个load方法:

 

	public void load() {
		User u = (User) getSession().load(User.class, 2);
		System.out.println(u);
	}

 

 

那么就会发现,多次调用该方法,但是执行的SQL语句,只执行了一次,没有多次执行,这就表明二级缓存起作用啦。

 

注意,session  的 load方法会使用缓存,但是query 的 list 方法只会往缓存中放数据,不会从缓存取数据,所以使用list是不行的,会发出多次SQL语句

 

要解决list的缓存问题,就用到了下面的查询缓存了。

 

查询缓存:解决相同SQL语句的多次执行问题,注意,SQL语句不同的话,是不能使用二级缓存和查询缓存的。

 

同时,查询缓存依赖于二级缓存,所以需要配置二级缓存:

 

 

		<!-- use query cache -->
		<property name="hibernate.cache.use_query_cache">true</property>
		<!-- use second level cache -->
		<property name="hibernate.cache.use_second_level_cache">true</property>
		<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

 

 

其它的同二级缓存,但是需要额外添加的操作就是,在query的list操作之前,需要调用setCacheable(true) :

 

 

session.createQuery(hql).setCacheable(true).list();

 

 

这样就可以实现相同SQL语句的查询缓存了。

 

 

 

 

 

 

 

 

 

 

 

下面贴上部分代码:

 

applicationContext.xml :

 

 

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<!-- 启动注入功能 -->
	<context:annotation-config />
	<!-- 启动扫描component功能 -->
	<context:component-scan base-package="com.tch.test.ssh" />
	<!-- 启动注解实物配置功能 -->
	<tx:annotation-driven transaction-manager="transactionManager" />
	<!-- 事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!--读取数据库配置文件  -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="mappingLocations">
			<list>
				<!-- <value>classpath*:com/tch/test/ssh/entity/*.hbm.xml</value> -->
			</list>
		</property>
		<property name="packagesToScan">
			<list>
				<value>com.tch.test.ssh.entity.annotation</value>
			</list>
		</property>
		<property name="configLocation">
			<value>classpath:hibernate.cfg.xml</value>
		</property>
	</bean>

	<!-- cache manager -->
	<bean id="cacheManager"
		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		<property name="shared" value="true" />
		<property name="configLocation" value="classpath:ehcache.xml" />
	</bean>
	<bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
		<property name="cacheManager" ref="cacheManager" />
		<property name="cacheName" value="root" />
	</bean>
</beans>

 

 

ehcache.xml :

 

 

<?xml version="1.0" encoding="UTF-8" ?>
<ehcache>

	<diskStore path="java.io.tmpdir"/>
	
	<defaultCache 
        eternal="false"
        timeToIdleSeconds="3600"
        timeToLiveSeconds="7200"
		maxElementsInMemory="10000" 
		overflowToDisk="true">
	</defaultCache>
	
	<cache   
        name="org.hibernate.cache.StandardQueryCache"    
        maxElementsInMemory="50"
        eternal="false"
        timeToIdleSeconds="3600"
        timeToLiveSeconds="7200"
        overflowToDisk="false"
    />   
  
    <cache   
        name="org.hibernate.cache.UpdateTimestampsCache"
        maxElementsInMemory="5000"
        eternal="false"
        timeToIdleSeconds="3600"
        timeToLiveSeconds="7200"
        overflowToDisk="false"
    />
</ehcache>

 

 

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>
		<property name="hibernate.connection.provider_class">org.hibernate.connection.ProxoolConnectionProvider</property>
		<property name="hibernate.proxool.xml">proxool.xml</property>
		<property name="hibernate.proxool.pool_alias">local_proxool</property>
		<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
		<property name="current_session_context_class">thread</property>
		<!-- use query cache -->
		<property name="hibernate.cache.use_query_cache">true</property>
		<!-- use second level cache -->
		<property name="hibernate.cache.use_second_level_cache">true</property>
		<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
		<property name="show_sql">true</property>
		<property name="hbm2ddl.auto">update</property>
	</session-factory>
</hibernate-configuration>

 

 

proxool.xml (数据库连接池的配置,和本文无关):

 

 

<?xml version="1.0" encoding="UTF-8"?>
<something-else-entirely>
  <proxool>
  
    <alias>local_proxool</alias>
    <driver-url>jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull</driver-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <driver-properties>
      <property name="user" value="root"/>
      <property name="password" value="root"/>
    </driver-properties>
    
    <house-keeping-sleep-time>90000</house-keeping-sleep-time>
   
    <house-keeping-test-sql>select CURRENT_DATE</house-keeping-test-sql>
     
    <prototype-count>4</prototype-count>
   
    <simultaneous-build-throttle>50</simultaneous-build-throttle>
   
    <maximum-connection-count>300</maximum-connection-count>
   
    <minimum-connection-count>2</minimum-connection-count>
   
    <maximum-connection-lifetime>3600000</maximum-connection-lifetime>
  </proxool>
</something-else-entirely>

 

 

 

struts.xml :(个人测试使用的SSH的项目)

 

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
	<constant name="struts.devMode" value="true" />
	<package name="default" namespace="/" extends="struts-default">
		
		<action name="show" class="userAction" method="show">
			<result>/WEB-INF/pages/User.jsp</result>
		</action>
		<action name="load" class="userAction" method="load">
			<result>/WEB-INF/pages/User.jsp</result>
		</action>
		
	</package>
</struts>

 

 

 

其中后台的load对应的action最终调用的DAO层的load方法:

 

 

	@Override
	public void load() {
		User u = (User) getSession().load(User.class, 2);
		System.out.println(u);
	}

 

 

多次调用该方法,会发现,只执行了一次SQL,这就是缓存的作用啦

 

后台的show对应的action最终调用的DAO层的show方法:

 

@Override
	public List  show() {
		return getSession().createQuery("from User").setCacheable(true).list();
	}

 

其中User类:

 

package com.tch.test.ssh.entity.annotation;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;


/**
 * User entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name="user")
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class User implements java.io.Serializable {

	// Fields


	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Integer id;
	private String name;
	private String password;
	//private Set<Priority> priorities;

	// Constructors

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password
				 + "]";
	}

	/** default constructor */
	public User() {
	}

	/** full constructor */
	public User(String name, String password) {
		this.name = name;
		this.password = password;
	}

	// Property accessors

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}


	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

 

 

 

好了,不早了,睡觉。。。

 

 

 

 

 

 

  • z.rar (38.9 KB)
  • 下载次数: 4
分享到:
评论

相关推荐

    spring3 hibernate4 ehcache实例

    而Ehcache则是一个广泛使用的内存缓存系统,能够提高数据访问效率,降低数据库负载。 本文将详细介绍如何在Spring3和Hibernate4环境下整合Ehcache,实现数据缓存功能,以提高应用性能。 1. **Spring3与Hibernate4...

    Hibernate + EhCache 实现数据缓存的处理

    本篇将详细探讨如何使用Hibernate ORM框架结合EhCache实现数据缓存的处理,从而提高系统的响应速度。 Hibernate是一个流行的Java持久化框架,它提供了一种便捷的方式来映射对象关系模型(ORM)到关系数据库。然而,...

    hibernate所需的ehcache的相关jar包,一共3个jar包

    Ehcache是一种广泛使用的开源Java缓存解决方案,它与Hibernate紧密结合,提供了第二级缓存的支持。本压缩包包含的是Hibernate使用Ehcache所需的核心jar包,一共三个,确保了Hibernate能够有效地利用缓存提升性能。 ...

    Spring+Hibernate+ehcache整合

    1. **Spring配置**:Spring的配置文件(如`applicationContext.xml`)会定义bean,包括数据源、SessionFactory(Hibernate)、缓存管理器(Ehcache)以及业务层和服务层的组件。通过依赖注入,Spring将这些组件装配...

    springmvc4+spring4+hibernate5.1.3+二级缓存ehcache+fastjson配置

    Ehcache是Hibernate的一个可选二级缓存插件,用于存储数据库查询结果,减少对数据库的直接访问。当相同的数据再次被请求时,可以从缓存中快速获取,提高系统响应速度。在不使用缓存的情况下,可以通过配置关闭。 5...

    在Spring+Hibernate集成环境中使用EhCache缓存

    在Spring和Hibernate集成的开发环境中,使用EhCache作为缓存机制是常见的优化策略,它能够显著提升应用程序的性能和响应速度。EhCache是一款开源的、高性能的、内存级的分布式缓存解决方案,适用于Java应用程序。...

    spring、 spring mvc、 hibernate、 ehcache Java后台框架

    Ehcache还可以与Spring集成,方便地在Spring应用中使用缓存功能。 在实际项目中,这四个框架的整合使用能够构建出高性能的Java后台系统。Spring作为基础架构,负责管理和协调各个组件;Spring MVC处理HTTP请求,...

    Hibernate_EHcache.doc

    本文将详细讲解如何在Hibernate中整合Ehcache,并探讨其配置和使用方法。 一、Ehcache的集成 1. 引入Ehcache库:首先,我们需要将Ehcache的jar包(如ehcache-1.2.3.jar)添加到项目的类路径(classpath)中。这...

    hibernate+ehcache代码示例

    Hibernate是一个强大的对象关系映射(ORM)框架,它简化了数据库操作,而Ehcache则是一种高效的分布式缓存系统,常用于提高数据访问速度和减轻数据库压力。 **Hibernate** 是一个流行的ORM框架,它允许开发者使用...

    hibernate-ehcache-starter:基于hibernate的ehcache应用启动器

    Hibernate是一个强大的对象关系映射(ORM)工具,允许开发者用Java对象来操作数据库,而Ehcache则是一个广泛使用的内存缓存解决方案,用于提高应用程序的性能和响应速度。 在Java开发中,特别是在处理大量数据或者...

    spring boot 使用jsp 集成hibernate+shiro+ehcache项目分享

    【Spring Boot 使用 JSP 集成 Hibernate+Shiro+Ehcache 项目详解】 Spring Boot 是一个基于 Spring 框架的高度集成了多种技术的开发工具,它简化了配置过程,使得开发人员能够快速构建可运行的应用程序。在这个项目...

    hibernate缓存机制

    Hibernate缓存机制是提高应用程序性能的关键技术之一,它通过存储数据副本减少对物理数据库的访问。缓存可以分为两层:第一级缓存和第二级缓存。 **第一级缓存**是内置在Session中的,它是不可卸载的,也称为...

    Hibernate缓存,性能优化

    本文将深入探讨Hibernate缓存的原理、类型及其对性能优化的影响。 ### Hibernate缓存原理 Hibernate缓存主要分为一级缓存和二级缓存。一级缓存,也称为会话缓存(Session Cache),是默认启用的,由Hibernate自动...

    Hibernate二级缓存(Ehcache)

    【标题】:“Hibernate二级缓存(Ehcache)” 【正文】: Hibernate是一个流行的Java对象关系映射(ORM)框架,它允许开发者用面向对象的方式来处理数据库操作。然而,随着应用规模的扩大,性能优化变得至关重要,...

    Hibernate缓存与spring事务详解

    **标题:“Hibernate缓存与Spring事务详解”** 在IT领域,尤其是Java开发中,Hibernate作为一款流行的ORM(对象关系映射)框架,极大地简化了数据库操作。而Spring框架则以其全面的功能,包括依赖注入、AOP(面向切...

    hibernate缓存

    ### Hibernate缓存机制及优化策略 #### 一、概述 Hibernate作为一款优秀的对象关系映射(ORM)框架,在Java开发领域被广泛应用于数据库操作。它提供了丰富的缓存机制来提高应用性能并降低数据库访问压力。本文将...

    Hibernate缓存详解

    本文将详细讲解Hibernate缓存的原理、类型以及使用方法。 ### 1. Hibernate缓存概述 缓存是存储在内存中的临时数据,当应用程序需要数据时,首先从缓存中查找,而不是直接查询数据库。这样可以减少网络延迟,提高...

Global site tag (gtag.js) - Google Analytics