GIN 发表于 2013-8-20 22:54:51

Hibernate && ehcache 缓存配置(注解方式)

本帖最后由 GIN 于 2013-8-21 08:56 编辑

ms注解是种流行,越来越多的注解,越来越多的零配置1.首先设置EhCache,建立配置文件ehcache.xml,默认的位置在class-path,可以放到你的src目录下:<xml version="1.0" encoding="UTF-8"?>   
<ehcache>   
 <diskStore path="java.io.tmpdir"/>   
  <defaultCache   
   maxElementsInMemory="10000"   
   eternal="false"   
   
   overflowToDisk="true"   
   
   timeToIdleSeconds="300"   
   timeToLiveSeconds="180"   
   diskPersistent="false"   
   diskExpiryThreadIntervalSeconds= "120"/>   
<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上配置。@Entity   
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)   
public class Forest { ... }   


@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)   
@JoinColumn(name="CUST_ID")   
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)   
public SortedSet getTickets() {   
    return tickets;   
}   


@Cache(   
    CacheConcurrencyStrategy usage();               (1)   
    String region() default "";                     (2)   
    String include() default "all";                   (3)   
)   


(1) usage: 提供缓存对象的事务隔离机制,可选值有以下几种(NONE, READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL)
ehcache不支持transactional,其他三种可以支持。

read-only:无需修改, 那么就可以对其进行只读 缓存,注意,在此策略下,如果直接修改数据库,即使能够看到前台显示效果,但是将对象修改至cache中会报error,cache不会发生作用。另:删除记录会报错,因为不能在read-only模式的对象从cache中删除。
read-write:需要更新数据,那么使用读/写缓存 比较合适,前提:数据库不可以为serializable transaction isolation level(序列化事务隔离级别)
nonstrict-read-write:只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见),也不需要十分严格的事务隔离,那么比较适合使用非严格读/写缓存策略。

(2) region (optional): 指定缓存的区域,默认是类的全限定名。利用缓存区域,可以更精确的指定每个区域的缓存超前策略。如果指定了缓存区域前缀(在hibernate.cfg.xml中设置cache.region_prefix属性为一个字符串),则所有的缓存区域名前将加上这个前缀。hbm文件查找cache方法名的策略:先查找ehcache.xml中的name的属性值,如果有个类是com.yybean.Foo,则使用ehcache.xml里面配置的name名为com.yybean.Foo的cache,

like:<cache name="com.yybean.Foo …如果不存在与类名匹配的cache名称,则用defaultCache。

如果Foo包含set集合,则需要另行指定其cache
(3) include (optional): all to include all properties, non-lazy to only include non lazy properties (default all).
调试时候使用log4j的log4j.logger.org.hibernate.cache=debug,更方便看到ehcache的操作过程,主要用于调试过程,实际应用发布时候,请注释掉,以免影响性能。
页: [1]
查看完整版本: Hibernate && ehcache 缓存配置(注解方式)