Hibernate4 + ehcache.

开篇先写结论:
Hibernate4 想使用 ehcache 时做二级缓存时,不使用 EHCache 提供的: hibernate.cache.region.factory_class
请无视 EHcache 网站上的 document , 那是针对 Hibernate 3.X 的.
Hibernate 4.X 有自己对其他 Cache 框架的支持.


具体修改的地方:
1.Hibernate Properties 配置.
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory


2. Maven pom 文件.
* 去掉 ehcache-core 依赖.
* 添加 cglib 依赖.
* 添加 hibernate-ehcache 依赖.
    (这个会获取它所依赖的 ehcache 版本,同样有其他 cache 缓存框架的支持, oscach jbossCache等 )

3. your_ehcache.xml
e.g:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
	<defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600"
		overflowToDisk="false">
	</defaultCache>
	<cache name="org.hibernate.cache.internal.StandardQueryCache" maxElementsInMemory="5" eternal="false" timeToLiveSeconds="120">
	</cache>
	<cache name="org.hibernate.cache.spi.UpdateTimestampsCache" maxElementsInMemory="5000" eternal="true">
	</cache>
</ehcache>


4. Java Class
e.g.
@Entity
@Table(name = "t_user")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User{...}


PS: 如果按照原来方式配置,可能会出现以下异常:

Caused by: java.lang.NoClassDefFoundError: org/hibernate/cache/TimestampsRegion
Caused by: java.lang.ClassNotFoundException: org.hibernate.cache.EntityRegion

猜你喜欢

转载自suene.iteye.com/blog/1753372