Hibernate Annotation 中配置EhCache缓存

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

  1. xml version="1.0" encoding="UTF-8"?>  
  2. <ehcache>  
  3.  <diskStore path="java.io.tmpdir"/>    
  4.   <defaultCache  
  5.    maxElementsInMemory="10000"    
  6.    eternal="false"    
  7.   
  8.    overflowToDisk="true"    
  9.   
  10.    timeToIdleSeconds="300"    
  11.    timeToLiveSeconds="180"    
  12.    diskPersistent="false"  
  13.    diskExpiryThreadIntervalSeconds"120"/>    
  14. ehcache>  

  2.  在Hibernate配置文件中设置:


<hibernate-configuration>

<session-factory>……<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property><property name="cache.use_second_level_cache">true</property>……</session-factory></hibernate-configuration>
        此外,可以把cache.use_second_level_cache设置为false关闭所有的hibernate二级缓存。但此属性对指定<cache>的类缺省为true。

 

   3.  为了使用二级缓存,需要在每一个Hibernate Entity上配置。


    import org.hibernate.annotations.Cache;
    import org.hibernate.annotations.CacheConcurrencyStrategy;
  1. @Entity  
  2. @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)   
  3. public class Forest { ... }  
  1. @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)   
  2. @JoinColumn(name="CUST_ID")   
  3. @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)   
  4. public SortedSet getTickets() {   
  5.     return tickets;   
  6. }  
  1. @Cache(   
  2.     CacheConcurrencyStrategy usage();                 (1)   
  3.     String region() default "";                       (2)   
  4.     String include() default "all";                   (3)   
  5. )  

(1) usage: 提供缓存对象的事务隔离机制,可选值有以下几种
(NONE, READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL)

(2) region (optional): 指定缓存的区域,默认是类的全限定名。利用缓存区域,可以更精确的指定每个区域的缓存超前策略。如果指定了缓存区域前缀(在 hibernate.cfg.xml中设置cache.region_prefix属性为一个字符串),则所有的缓存区域名前将加上这个前缀。
(3) include (optional): all to include all properties, non-lazy to only include non lazy properties (default all).

如果不是使用annotation的话,则是在Hbm文件中添加cache usage="read-only"

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值