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.cache.provider_class=org.hibernate.cache.EhCacheProvider
- hibernate.cache.use_query_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<ticket></ticket> getTickets() {
- return tickets;
- }
- @Cache(
- CacheConcurrencyStrategy usage(); (1)
- String region() default ""; (2)
- String include() default "all"; (3)
- )
(1) usage: the given cache concurrency strategy (NONE, READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL)
(2) region (optional): the cache region (default to the fqcn of the class or the fq role name of the collection)
(3) include (optional): all to include all properties, non-lazy to only include non lazy properties (default all).
如果不是使用annotation的话,则是在Hbm文件中添加cache usage="read-only"<cache usage="read-only"></cache>
4. 如果需要“查询缓存”,还需要在使用Query或Criteria()时设置其setCacheable(true);属性