---
title: "hibernate 二级缓存 个人总结"
author: "network-eagle"
date: "2010-03-30T14:36:57Z"
tags: []
categories: ["企业架构"]
slug: "hibernate"
draft: false
lastmod: "2010-03-30T14:38:42Z"
id: 628183
url: "https://network-eagle.iteye.com/blog/628183"
---

今天特地的回顾了一下hibernate 的二级缓存， 我平常用到的是两种
1：   ehcache  
    1.1 首先配置 ehcache.xml  当然也可以默认 也可以自定义 
```java
<cache name="Student"
		maxElementsInMemory="80" eternal="false" overflowToDisk="false"
		timeToIdleSeconds="80" timeToLiveSeconds="80"   /> 
```

     说明： name 就是自定义的名称    
             maxElementsInMemory   缓存存储的总记录量 
             eternal  缓存是否永远不销毁 
             overflowToDisk  当缓存到达总数后是否覆盖原来的
             timeToIdleSeconds   当缓存空闲时间超过该值 则缓存自动销毁 感觉上没多大用处 可能是测试的时候 缓存量的问题 
             timeToLiveSeconds 缓存创建之后，到达该缓存自动销毁 同上
    1.2 让后在用到的 hibernate映射文件中 添加 
```java
<hibernate-mapping>
    <class name="com.eagle.model.cache.Student" table="t_student" >
      [u]<cache usage="read-write" region="Student"  />[/u]   
        ………省略 ……………    </class>
</hibernate-mapping>
```

   表示该类要用缓存   另 可以在 hibernate.cfg.xml 添加
```java
<class-cache class="com.eagle.model.cache.Student"
			usage="read-write" region="Student" />
```
  可以在hibernate.cfg.xml 统一管理那里类用到了缓存  
 说明  region  指定使用哪个缓存机制。这个在ehcache 中所配置的
       usage   这个是必须的  缓存的策略: transactional、 read-write、 nonstrict-read-write或 read-only。
    1.3    在hibernate.cfg.xml 数据连接池 别忘记加上
    
```java
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
		
		<property name="hibernate.cache.use_second_level_cache">true</property>
```



2 如果 你用的是 org.hibernate.cache.HashtableCacheProvider  
   就只需要在需要用的hibernate映射文件中 添加 <cache usage="read-write" />当然这个也可以跟 上面的一样可以统一在配置文件中管理起来 。