---
title: "Hibernate4 + ehcache."
author: "suene"
date: "2012-12-24T19:40:20Z"
tags: []
categories: ["企业架构"]
slug: "hibernate4-ehcache"
draft: false
lastmod: "2012-12-28T10:46:27Z"
id: 1753372
url: "https://suene.iteye.com/blog/1753372"
---

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

```java

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:

```java

<?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.

```java

@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