`
chxiaowu
  • 浏览: 241859 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Hibernate和Spring的缓存机制

 
阅读更多

hibernate 配置ehcache.xml文。

在Hibernate配置文件中设置:

<!--  Hibernate SessionFactory  -->
    
< bean id = " sessionFactory "   class = " org.springframework.orm.hibernate3.LocalSessionFactoryBean " >
        
< property name = " dataSource "  ref = " dataSource " />
        
< property name = " mappingResources " >
        
< list >
            
< value > com / ouou / model / Videos.hbm.xml </ value >    
         
</ list >
         
</ property >
        
< property name = " hibernateProperties " >
            
< props >
                
< prop key = " hibernate.dialect " > org.hibernate.dialect.MySQLDialect </ prop >
                
< prop key = " hibernate.current_session_context_class " > thread </ prop >
                
< prop key = " hibernate.cglib.use_reflection_optimizer " > false </ prop >
                
< prop key = " hibernate.query.substitutions " > true   ' Y ' false   ' N ' </ prop >
                
<!-- add ehcache -->
                
< prop key = " hibernate.cache.provider_class " > org.hibernate.cache.EhCacheProvider </ prop >
                
< prop key = " hibernate.cache.use_query_cache " > false </ prop ><!--  是否使用查询缓存  -->
                
<!--
                
< prop key = " hibernate.cache.provider_configuration_file_resource_path " >/ ehcache.xml </ prop >
                
< prop key = " hibernate.show_sql " > true </ prop >
                
-->
                
<!--< prop key = " hibernate.transaction.auto_close_session " > true </ prop >-->
                
< prop key = " connection.provider_class " > org.hibernate.connection.C3P0ConnectionProvider </ 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 " > 25 </ prop >
                
<!--
                
< prop key = " hibernate.connection.pool_size " > 10 </ prop >
                
-->
            
</ props >
        
</ property >
    
</ bean >


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

2.首先设置EhCache,建立配置文件ehcache.xml,默认的位置在class-path,可以放到你的src目录下:


    
< defaultCache
        maxElementsInMemory
= " 10000 "
        eternal
= " false "
        overflowToDisk
= " true "
        timeToIdleSeconds
= " 120 "
        timeToLiveSeconds
= " 120 "
        diskPersistent
= " false "
        diskExpiryThreadIntervalSeconds
= " 120 " />
    
< cache name = " org.hibernate.cache.UpdateTimestampsCache "  maxElementsInMemory = " 5000 "  
     eternal
= " true "  overflowToDisk = " true " />
    
< cache name = " org.hibernate.cache.StandardQueryCache "  maxElementsInMemory = " 5 "  eternal = " false "
    timeToLiveSeconds
= " 120 "  overflowToDisk = " true " />
    
< cache name = " userCache "  maxElementsInMemory = " 100000 "  eternal = " false "  timeToIdleSeconds =
        "
600 "    timeToLiveSeconds = " 600 "  overflowToDisk = " false "  diskPersistent = " false " />
    
< cache name = " com.ouou.webapp.util.OuouMethodIntecepter "  maxElementsInMemory = " 100000 "  
    eternal
= " false "  timeToIdleSeconds = " 600 "  timeToLiveSeconds = " 600 "  overflowToDisk = " false "
    diskPersistent
= " false " />
    
< cache name = " bbcode "  maxElementsInMemory = " 100000 "  eternal = " false "  timeToIdleSeconds = " 600 "
    timeToLiveSeconds
= " 600 "  
    overflowToDisk
= " false "  diskPersistent = " false " />
    
< cache name = " com.ouou.model.Videos "  maxElementsInMemory = " 10000 "   eternal = " false "  
    overflowToDisk
= " false "  timeToIdleSeconds = " 120 "  timeToLiveSeconds = " 120 "  diskPersistent = " false " />
    
< cache name = " com.ouou.model.Tags "  maxElementsInMemory = " 10000 "   eternal = " false "
    overflowToDisk
= " false "  timeToIdleSeconds = " 120 "  timeToLiveSeconds = " 120 "  diskPersistent = " false " />
</ ehcache >
以com.ouou.model.Videos为例子
在Videos.hbm.xml中配置:
<class name="Videos" table="TEST" lazy="false">
  <cache usage="read-write" region="ehcache.xml中的name的属性值"/>注意:这一句需要紧跟在class标签下面,其他位置无效。
hbm文件查找cache方法名的策略:如果不指定hbm文件中的region="ehcache.xml中的name的属性值",则使用name名为com.ouou.model.Videos的cache,
如果不存在与类名匹配的cache名称,则用defaultCache。
如果Videos包含set集合,则需要另行指定其cache
例如Videos包含Tags集合,则需要
添加如下配置到ehcache.xml中
<cache name="com.ouou.model.Tags"
        maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120"
        timeToLiveSeconds="120" overflowToDisk="false" />
另,针对查询缓存的配置如下:
<cache name="org.hibernate.cache.UpdateTimestampsCache"
        maxElementsInMemory="5000"
        eternal="true"
        overflowToDisk="true"/>
<cache name="org.hibernate.cache.StandardQueryCache"
        maxElementsInMemory="10000"
        eternal="false"
        timeToLiveSeconds="120"
        overflowToDisk="true"/>
3、 选择缓存策略依据:
<cache  usage="transactional|read-write|nonstrict-read-write|read-only" (1)/>
ehcache不支持transactional,其他三种可以支持。
read-only:无需修改,那么就可以对其进行只读缓存,注意,在此策略下,如果直接修改数据库,即使能够看到前台显示效果,
但是将对象修改至cache中会报error,cache不会发生作用。另:删除记录会报错,因为不能在read-only模式的对象从cache中删除。
read-write:需要更新数据,那么使用读/写缓存 比较合适,前提:数据库不可以为serializable transaction isolation level
(序列化事务隔离级别)
nonstrict-read-write:只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见),也不需要十分严格的事务隔离,
那么比较适合使用非严格读/写缓存策略。

4、调试时候使用log4j的log4j.logger.org.hibernate.cache=debug,更方便看到ehcache的操作过程,主要用于调试过程,实际应用发布时候,请注释掉,以免影响性能。

5、 使用ehcache,打印sql语句是正常的,因为query cache设置为true将会创建两个缓存区域:一个用于保存查询结果集 (
org.hibernate.cache.StandardQueryCache);另一个则用于保存最近查询的一系列表的时间戳(org.hibernate.cache.UpdateTimestampsCache)。
请注意:在查询缓存中,它并不缓存结果集中所包含的实体的确切状态;它只缓存这些实体的标识符属性的值、以及各值类型的结果。
需要将打印sql语句与最近的cache内容相比较,将不同之处修改到cache中,所以查询缓存通常会和二级缓存一起使用。

--------------------------------------------------------------------------------------------------

spring 3.0.5 发布后,公司使用Spring MVC +Hibernate 3.5 做项目,其中用到了缓存机制,spring 3.0.5 中ehcache配置方法很简单,其中缓存机制很细颗粒化,可以具体到把每个方式的返回值做缓存,好了不说废话下面开始:

需要JAR包:
第一:spring 3.0.5 其中JAR;
第二:另外需要增量JAR包(cglib-2.2.jar,ehcache-spring-annotations-1.1.2.jar)注意版本;

其中applicationContext.xml 其中配置:
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.0.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring  
  http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">

<ehcache:annotation-driven cache-manager="ehCacheManager" />
 
 <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> 
       <property name="configLocation" value="classpath:ehcache.xml" /> 
   </bean>

加到你的文件中去,上边是头信息自己可以比照下,没有的加进去;
在你的 src 目录下新建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">
 <diskStore path="java.io.tmpdir" />
 <defaultCache eternal="false"
   maxElementsInMemory="1000"
   overflowToDisk="false"
   diskPersistent="false"
   timeToIdleSeconds="0"
   timeToLiveSeconds="600"
   memoryStoreEvictionPolicy="LRU" />

 <cache name="departCache"
   eternal="false"
   maxElementsInMemory="100"
   overflowToDisk="false"
   diskPersistent="false"
   timeToIdleSeconds="0"
   timeToLiveSeconds="300"
   memoryStoreEvictionPolicy="LRU" />

</ehcache>

其中里边详细配置自己可以去上网搜下;

这样基本上配置完成了:

DAO层缓存:例如下边这个方法的返回值需要缓存:

@SuppressWarnings("unchecked")
 //spring 3 基于注解ehcache缓存配置;
 @Cacheable(cacheName="departCache")
 public List<AppDepart> getChildDepart(Integer id) throws Exception {
  return  this.getHibernateTemplate().find("from AppDepart  where state=1 and idParent="+id);
 }
 
@Cacheable(cacheName="departCache") 加上这句话,其中cacheName 对应ehcache.xml  中的<cache name="departCache"

这样这个方法返回值就可以被缓存起来的了,但是怎么样把缓存数据和数据库中的数据实现同步呢?

如果对这个PO做update ,save,delete 可以实现这样策略如下:

@Transactional(propagation = Propagation.REQUIRED)
 //设定spring的ecache缓存策略,当编辑机构时候,把缓存全部清除掉,以达到缓存那数据同步;
 @TriggersRemove(cacheName="departCache",removeAll=true)
 public boolean editDepart(String depno, String depName) {
  boolean flag = false;
  try {
   AppDepart depart = departDao.getAppdepart(depno);
   depart.setDepName(depName);
   departDao.update(depart);
   flag = true;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return flag;
 }

好了到此配置完毕,但是更加详细缓存配置策略需要研究(例如:当update数据时候,不全部清掉缓存,就可以达到与数据库同步效果)
以下配置经本人完成测试通过(只限于本版本)。

分享到:
评论

相关推荐

    hibernate和spring整合Java项目

    在Java开发领域,Hibernate和Spring是两个非常重要的开源框架,它们分别在对象关系映射(ORM)和依赖注入(DI)方面发挥着关键作用。整合这两个框架,可以创建出高效、灵活且易于维护的Java应用。本文将深入探讨...

    Spring集成的Hibernate配置二级缓存

    在企业级Java应用开发中,Spring和...总之,合理利用Hibernate的二级缓存机制,结合Spring的管理能力,可以有效地提升Java应用的性能。通过优化缓存配置和策略,可以在不牺牲数据一致性的情况下,达到良好的用户体验。

    最新Struts和Hibernate和Spring经典面试题

    以下是对 Struts、Hibernate 和 Spring 的经典面试题的总结,涵盖了这些框架的工作机制、优点、缓存机制、查询方式、优化方法等知识点。 Hibernate 1. Hibernate 工作原理及为什么要用? Hibernate 工作原理包括...

    Hibernate缓存与spring事务详解

    本篇文章将深入探讨Hibernate的缓存机制和Spring的事务管理,以帮助开发者更好地理解和利用这两个强大的工具。 **一、Hibernate缓存** 1. **第一级缓存:Session缓存** - Hibernate的每个Session都有一个内置的...

    Hibernate和spring集成

    Hibernate提供了缓存机制,如一级缓存(Session级别的缓存)和二级缓存(SessionFactory级别的缓存)。Spring允许我们在配置中开启和配置二级缓存,以提高数据访问效率。 9. **异常处理** Spring将Hibernate的...

    Struts2+Hibernate+Spring课件 张志峰版

    它支持懒加载、缓存机制、事务管理和多种数据库平台,大大提高了开发效率。 **Spring** 框架则是一个全面的企业级应用开发框架,它包括依赖注入(DI)、面向切面编程(AOP)、数据访问/集成、Web、测试等多个模块。...

    struts+hibernate+spring源码

    同时,事务管理(Transaction)和缓存(Cache)机制也是重要的学习点,它们对于提高性能和保证数据一致性至关重要。 **Spring框架源码探讨:** Spring以其IoC(Inversion of Control)和AOP(Aspect-Oriented ...

    在线音乐网站(Struts2+hibernate+spring)

    它通过HQL(Hibernate查询语言)或SQL语句进行数据查询,提供了事务管理和缓存机制,提高了数据访问的性能。 【Spring】框架则是一个全面的企业级应用开发框架,包括依赖注入(DI)、面向切面编程(AOP)、数据访问...

    hibernate和Spring源码

    4. **缓存机制**:Hibernate支持二级缓存,可以提高数据读取效率,理解缓存策略和使用时机是提高系统性能的关键。 5. **实体状态管理**:Hibernate管理实体的瞬时、持久化、脱管等状态,理解这些状态转换有助于避免...

    Hibernate、Spring和Struts工作原理及使用理由

    **缓存机制**: - **一级缓存**:内部缓存,每个Session有自己的缓存,生命周期与Session相同。 - **二级缓存**:可选的全局缓存,支持应用级和分布式缓存,适用于特定场景。 **查询方式**: - SQL:直接编写SQL...

    整合struts+hibernate+spring应用开发详解 part1

    Hibernate支持事务管理、缓存机制以及多种数据库的连接,极大地提高了开发效率。 Spring框架则是企业级应用的核心,它提供了一个全面的基础设施,包括依赖注入(DI)、面向切面编程(AOP)、数据访问、事务管理、...

    Hibernate和Spring中文参考手册

    此外,还会涉及事务管理、缓存机制、查询语言HQL和Criteria API的使用等。 Spring框架则是Java企业级应用的核心框架,它提供了一个全面的基础设施,支持开发可测试、松耦合的应用。Spring的核心特性包括依赖注入...

    Struts2_Hibernate_Spring基础教程

    它支持事务管理、缓存机制,以及多种数据库方言,增强了应用程序的可移植性。 **Spring** 框架是JavaEE应用的核心组件,它提供了依赖注入(DI)和面向切面编程(AOP)等核心功能,有助于减少代码间的耦合。Spring还...

    SSH整合 struts+hibernate+spring

    在软件开发领域,特别是Java Web开发中,Struts、Spring 和 Hibernate 被广泛地应用于构建复杂的应用程序。这三大框架各有所长,分别在不同的层面发挥作用。为了更好地利用这些框架的优势,开发者通常会采用SSH...

    基于Struts+Hibernate+Spring的Web_应用开发

    - **高性能**:支持数据缓存、连接池、批量处理等优化机制。 - **跨平台**:支持多种数据库和Web服务器,易于移植。 **2. 实际应用** - 学习如何使用Hibernate进行实体类的定义、映射文件的编写、配置文件的设置...

    hibernate和spring源代码

    例如,当遇到性能瓶颈时,可以查看缓存机制以优化数据访问;在设计业务逻辑时,可以借鉴AOP和DI的思想来实现松耦合和高内聚。同时,理解源码也有助于掌握最新的技术趋势,如Spring Boot和Spring Cloud,它们都是基于...

    为Spring集成的Hibernate配置二级缓存

    首先,我们需要了解Hibernate的二级缓存机制。一级缓存是每个Session内部的缓存,而二级缓存则是SessionFactory级别的,它可以被多个Session共享。二级缓存主要由第三方缓存提供者如Ehcache、Infinispan等实现,它们...

    基于Struts,Hibernate和Spring的J2EE架构研究

    - **缓存机制**:提供一级缓存和二级缓存,有效提升性能。 ##### 2.3 应用程序框架Spring Spring是一个轻量级的IoC容器和AOP框架,旨在简化企业级应用的开发。Spring的核心模块包括: - **IoC容器**:负责创建和...

    FF.MSOL.SOA.rar_jpa hibernate_spring hibernate_spring mvc

    此外,Hibernate还包括了实体管理、缓存机制、事务处理等功能,是Java世界中广泛使用的持久化框架。 Spring是一个全面的Java企业级应用开发框架,它提供了依赖注入(DI)和面向切面编程(AOP)等核心特性,极大地...

    Eclipse源码(整合struts,hibernate和spring)

    它支持事务管理、缓存机制以及复杂的查询功能。 Spring框架是一个全面的企业级应用开发框架,它不仅提供了依赖注入(DI)和面向切面编程(AOP)等核心特性,还涵盖了数据访问、Web应用、消息处理等多个领域。在本...

Global site tag (gtag.js) - Google Analytics