大量数据流动是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. Contoso 大学 - 7 – 处理并发

    原文 Contoso 大学 - 7 – 处理并发 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Microsoft's W ...

  2. PHP学习笔记 - 入门篇(4)

    PHP学习笔记 - 入门篇(4) 什么是运算符 PHP运算符一般分为算术运算符.赋值运算符.比较运算符.三元运算符.逻辑运算符.字符串连接运算符.错误控制运算符. PHP中的算术运算符 算术运算符主要 ...

  3. Linux rar

    http://www.vpsyou.com/2010/06/15/to-extract-rar-centos.html wget http://www.rarsoft.com/rar/rarlinux ...

  4. struts2使用struts2-bootstrap-plugin插件

    1.下载插件 http://code.google.com/p/struts2-bootstrap/ 2.添加maven依赖 <dependency> <groupId>com ...

  5. 【转】Qt使用自带的windeployqt 生成exe来发布软件

    集成开发环境 QtCreator 目前生成图形界面程序 exe 大致可以分为两类:Qt Widgets Application  和 Qt Quick Application.下面分别介绍这两类exe ...

  6. DB2删除数据时的小技巧

    大家对如何删除数据都不陌生,我们习惯性的这么写: 其实这么写性能并不好,尤其是删除大量数据的时候,要想获得更好的性能,可以采用如下方式: 那如果要把一个表的所有数据都删除了,该怎么办?有人可能会说,这 ...

  7. Mindjet.MindManager“参数错误”解决办法,适用于9.0、10.0和14.0

    MindManager出14.0版本了,但是在应用个别模板的时候会提示“参数错误”,然后自动关闭. 解决办法:   如果是win7系统,可以进入C:\Users\(用户名) \AppData\Loca ...

  8. json 语义分析

    json 中:元素与值用冒号 ":" 隔开元素与元素用逗号 "," 隔开{} 之间是一个对象, 对象可以层层嵌套[] 表示数组, 数组元素用逗号 ", ...

  9. linux内核中sys_poll()的简化分析

    app:poll or select; kernel: sys_poll(); do_sys_poll(struct pollfd __user *ufds, unsigned int nfds,st ...

  10. [Python 标准库]第一章 文本

    Chapter01 文本 1.1 string - 文本常量和模板 作用:包含处理文本的常量和类. 1.1.1 函数 capwords(s):字符串中所有单词首字母大写 maketrans():创建转 ...