大量数据流动是web应用性能问题常见的原因,而缓存被广泛的用于优化数据库应用。cache被设计为通过保存从数据库里load的数据来减少应用和数据库之间的数据流动。数据库访问只有当检索的数据不在cache里可用时才必要。hibernate可以用两种不同的对象缓存:first-level cache 和 second-level cache。first-level cache和Session对象关联,而second-level cache是和Session Factory对象关联。

        缺省地,hibernate已经使用基于每个事务的first-level cache。Hibernate用first-level cache主要是减少在一个事务内的sql查询数量。例如,如果一个对象在同一个事务内被修改多次,hibernate将只生成一个包括所有修改的UPDATE SQL语句。为了减少数据流动,second-level cache在Session Factory级的不同事务之间保持load的对象,这些对象对整个应用可用,不只是对当前用户正在运行的查询。这样,每次查询将返回已经load在缓存里的对象,避免一个或更多潜在的数据库事务。

下载ehcache,hibernate3.2必须要ehcache1.2以上才能支持。可以修改log4j配置文件log4j.logger.net.sf.hibernate.cache=debug查看日志

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:

        maxElementsInMemory            - 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.
        overflowToDisk                 - Sets whether elements can overflow to disk when the in-memory cache
                                         has reached the maxInMemory limit.

        The following attributes are optional:
        timeToIdleSeconds              - Sets the time to idle for an element before it expires.
                                         i.e. The maximum amount of time between accesses before an element expires
                                         Is only used if the element is not eternal.
                                         Optional attribute. A value of 0 means that an Element can idle for infinity.
                                         The default value is 0.
        timeToLiveSeconds              - Sets the time to live for an element before it expires.
                                         i.e. The maximum time between creation time and when an element expires.
                                         Is only used if the element is not eternal.
                                         Optional attribute. A value of 0 means that and Element can live for infinity.
                                         The default value is 0.
        diskPersistent                 - Whether the disk store persists between restarts of the Virtual Machine.
                                         The default value is false.
        diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value
                                         is 120 seconds.
        -->

    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        overflowToDisk="true"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120"/>
        
    <!-- See http://ehcache.sourceforge.net/documentation/#mozTocId258426 for how to configure caching for your objects -->
</ehcache>

2.applicationContext-hibernate.xml里Hibernate SessionFactory配置:

<!-- Hibernate SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation"><value>classpath:hibernate.cfg.xml</value></property>
        <!-- The property below is commented out b/c it doesn't work when run via
             Ant in Eclipse. It works fine for individual JUnit tests and in IDEA ??
        <property name="mappingJarLocations">
            <list><value>file:dist/appfuse-dao.jar</value></list>
        </property>
        -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">@HIBERNATE-DIALECT@</prop>
                <!--<prop key="hibernate.show_sql">true</prop>-->
                <prop key="hibernate.max_fetch_depth">3</prop>
                <prop key="hibernate.hibernate.use_outer_join">true</prop>
                <prop key="hibernate.jdbc.batch_size">10</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
                <!--
                <prop key="hibernate.use_sql_comments">false</prop>
                -->
                <!-- Create/update the database tables automatically when the JVM starts up
                <prop key="hibernate.hbm2ddl.auto">update</prop> -->
                <!-- Turn batching off for better error messages under PostgreSQL
                <prop key="hibernate.jdbc.batch_size">0</prop> -->
            </props>
        </property>
        <property name="entityInterceptor">
           <ref local="auditLogInterceptor"/>
        </property>
    </bean>

说明:如果不设置“查询缓存”,那么hibernate只会缓存使用load()方法获得的单个持久化对象,如果想缓存使用findall()、 list()、Iterator()、createCriteria()、createQuery()等方法获得的数据结果集的话,就需要设置hibernate.cache.use_query_cache true 才行

3.model类里采用Xdoclet生成*.hbm.xml里的cache xml标签,即<cache usage="read-only"/>

/**
* @hibernate.class table="WF_WORKITEM_HIS"
* @hibernate.cache usage="read-write"

*/

4.对于"query cache",需要在程序里编码:

        getHibernateTemplate().setCacheQueries(true);
        return getHibernateTemplate().find(hql);

【转】Spring+Hibernate+EHcache配置(一)的更多相关文章

  1. 转Spring+Hibernate+EHcache配置(二)

    Spring AOP+EHCache简单缓存系统解决方案 需要使用Spring来实现一个Cache简单的解决方案,具体需求如下:使用任意一个现有开源Cache Framework,要求可以Cache系 ...

  2. 转Spring+Hibernate+EHcache配置(三)

    配置每一项的详细作用不再详细解释,有兴趣的请google下 ,这里需要注意一点defaultCache标签定义了一个默认的Cache,这个Cache是不能删除的,否则会抛出No default cac ...

  3. Spring+Hibernate整合配置 --- 比较完整的spring、hibernate 配置

    Spring+Hibernate整合配置 分类: J2EE2010-11-25 17:21 16667人阅读 评论(1) 收藏 举报 springhibernateclassactionservlet ...

  4. Hibernate+EhCache配置二级缓存

    步骤: 第一步:加入ehcache.jar 第二步: 在src目录下新建一个文件,名为:ehcache.xml 第三步:在hibernate配置文件的<session-factory>下配 ...

  5. SSH(Struts+spring+hibernate)配置

    1.spring和struts 1)web.xml 配置spring的ContextLoaderListener(监听器) 配置Struts的StrutsPrepareAndExecuteFilter ...

  6. Hibernate4+EhCache配置二级缓存

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

  7. spring 实现事务配置的方式

    spring 中常用的两种事务配置方式以及事务的传播性.隔离级别 一.注解式事务 1.注解式事务在平时的开发中使用的挺多,工作的两个公司中看到很多项目使用了这种方式,下面看看具体的配置demo. 2. ...

  8. spring+hibernate 配置多个数据源过程 以及 spring中数据源的配置方式

    spring+hibernate 配置多个数据源过程 以及 spring中数据源的配置方式[部分内容转载] 2018年03月27日 18:58:41 守望dfdfdf 阅读数:62更多 个人分类: 工 ...

  9. spring中ehcache的配置和使用方法

    继续上篇,这篇介绍服务层缓存,ehcache一般的配置和用法 一.添加jar包引用 修改pom.xml文件,加入: <dependency> <groupId>org.spri ...

随机推荐

  1. ASP判断当前页面上是否有参数ID传递过来

    遇到了一个这样的ASP问题: 在当前页面上判断,是否有参数ID传递过来? 如果没有,显示“没有参数传递过来”. 如果有传递,但值为空,显示“存在参数,但参数为空” <% if (request( ...

  2. Linux C编程--打开和关闭流

    以下函数用于打开和关闭一个流.#include <stdio.h>FILE * fopen (const char *pathname, const char *opentype);int ...

  3. 转:SqlServer2008误操作数据(delete或者update)后恢复数据

    Sqlserver2008误操作数据(delete或者update)后恢复数据(转) 实际工作中,有时会直接在数据库中操作数据,比如对数据进行delete或者update操作,当进行这些操作的时候,如 ...

  4. Ubuntu Linux 分区简易教程

    关于Linux系统下的“分区”问题,对于新手来说一直是很头疼的.我来简单写一下,它的“分区”方法,规则. 声明:我为了让没有接触过Linux系统的人,理解更加简单.所以在言语表述上不是很规范,专业.我 ...

  5. java学习笔记_MIDI

    import javax.sound.midi.*; public class Midi { public void play(int instrument, int note) { try { Se ...

  6. Nodejs微信接口

    代码重要部分都已详细注释,test.js为实例,如果启动url请求,那么程序默认对json格式数据友好,如果有特殊需要,请自行修改返回数据的处理格式 大概功能简介为下: this._token 提供t ...

  7. jQuery 全选 反选 单击行改变背景色

    我先把CSS样式放出来,其实这个可以直接忽略 ;;font-size:12px;font-family:微软雅黑;} .datagrid{width:100%;} .datagird tr th{ba ...

  8. 弹性布局学习-详解 justify-content(三)

    弹性布局学习-详解 justify-content(三)

  9. lnmp全面优化集合nginx+mysql+php

    lnmp的全名是linux+nginx+mysql+php,既然是全面优化那我们就从linux系统的选择入手.debian系统可以算是 linux各分支中做的比较突出的一类,连谷歌都抛弃linux订制 ...

  10. DHT网络第一部分研究结果 加入长期在线的node

    源码:http://jijiea.com/upfile/DHT_Part1_How_To_Join_In_DHT.zip