---
title: " Hibernate缓存机制"
author: "xiaowei2002"
date: "2015-09-06T11:49:30Z"
tags: []
categories: ["企业架构"]
slug: "hibernate"
draft: false
lastmod: "2015-09-06T11:49:30Z"
id: 2240998
url: "https://xiaowei2002.iteye.com/blog/2240998"
---

**一、为什么要用hibernate缓存机制**    
Hibernate是一个持久层框架，经常访问物理数据库。为了降低应用程序对物理数据源访问的频次，从而提高应用程序的运行性能。缓存内的数据是对物理数据源中的数据的复制，应用程序在运行时从缓存读写数据，在特定的时刻或事件会同步缓存和物理数据源的数据。

**二、Hibernate缓存原理是怎样的？**

***1.Hibernate一级缓存又称为“Session的缓存”。***

Session内置不能被卸载，Session的缓存是事务范围的缓存（Session对象的生命周期通常对应一个数据库事务或者一个应用事务）。一级缓存中，持久化类的每个实例都具有唯一的OID（对象标识符）。

***2.Hibernate二级缓存又称为“SessionFactory的缓存”。***

由于SessionFactory对象的生命周期和应用程序的整个过程对应，因此Hibernate二级缓存是进程范围或者集群范围的缓存，有可能出现并发问题，因此需要采用适当的并发访问策略，该策略为被缓存的数据提供了事务隔离级别。  
第二级缓存是可选的，是一个可配置的插件，默认下SessionFactory不会启用这个插件。Hibernate提供了org.hibernate.cache.CacheProvider接口,它充当缓存插件与Hibernate之间的适配器。

***2.1什么样的数据适合存放到第二级缓存中？*** 　　  
1\) 很少被修改的数据 　　  
2\) 不是很重要的数据，允许出现偶尔并发的数据 　　  
3\) 不会被并发访问的数据 　　  
4\) 常量数据  
　　  
***2.2不适合存放到第二级缓存的数据？*** 　　  
1\) 经常被修改的数据 　　  
2\) 绝对不允许出现并发访问的数据，如财务数据，绝对不允许出现并发 　　  
3\) 与其他应用共享的数据。

**三、Session的延迟加载实现要解决两个问题：正常关闭连接和确保请求中访问的是同一个session。**

Hibernate session就是java.sql.Connection的一层高级封装，一个session对应了一个Connection。http请求结束后正确的关闭session（过滤器实现了session的正常关闭）；延迟加载必须保证是同一个session（session绑定在ThreadLocal）。

**四、Hibernate查找对象如何应用缓存？**

当Hibernate根据ID访问数据对象的时候，首先从Session一级缓存中查；查不到，如果配置了二级缓存，那么从二级缓存中查；如果都查不到，再查询数据库，把结果按照ID放入到缓存中，删除、更新、增加数据的时候，同时更新缓存。

**五、Hibernate的缓存机制如何应用？**

***5.1  一级缓存的管理:***

**evit(Object obj)：**  将指定的持久化对象从一级缓存中清除,释放对象所占用的内存资源,指定对象从持久化状态变为脱管状态,从而成为游离对象。  
**clear()：**  将一级缓存中的所有持久化对象清除,释放其占用的内存资源。  
**contains(Object obj)：** 判断指定的对象是否存在于一级缓存中。  
**flush()：** 刷新一级缓存区的内容,使之与数据库数据保持同步。

***5.2  一级缓存应用：***

**save()：**当session对象调用save()方法保存一个对象后，该对象会被放入到session的缓存中。  
**get()和load()：**当session对象调用get()或load()方法从数据库取出一个对象后，该对象也会被放入到session的缓存中。 使用HQL和QBC等从数据库中查询数据。

Java代码 [![复制代码](http://itxiaojiang.iteye.com/images/icon_copy.gif)](http://itxiaojiang.iteye.com/blog/2240654 "复制代码") [![收藏代码](http://itxiaojiang.iteye.com/images/icon_star.png)![](http://itxiaojiang.iteye.com/images/spinner.gif)]()

01. public class Client
02. {
03. public static void main(String\[] args)
04. {
05. Session session = HibernateUtil.getSessionFactory().openSession();
06. Transaction tx = null;
07. try
08. {
09. /\*开启一个事务\*/
10. tx = session.beginTransaction();
11. /\*从数据库中获取id="402881e534fa5a440134fa5a45340002"的Customer对象\*/
12. Customer customer1 = (Customer)session.get(Customer.class, "402881e534fa5a440134fa5a45340002");
13. System.out.println("customer.getUsername is"+customer1.getUsername());
14. /\*事务提交\*/
15. tx.commit();
16. System.out.println("-------------------------------------");
17. /\*开启一个新事务\*/
18. tx = session.beginTransaction();
19. /\*从数据库中获取id="402881e534fa5a440134fa5a45340002"的Customer对象\*/
20. Customer customer2 = (Customer)session.get(Customer.class, "402881e534fa5a440134fa5a45340002");
21. System.out.println("customer2.getUsername is"+customer2.getUsername());
22. /\*事务提交\*/
23. tx.commit();
24. System.out.println("-------------------------------------");
25. /\*比较两个get()方法获取的对象是否是同一个对象\*/
26. System.out.println("customer1 == customer2 result is "+(customer1==customer2));
27. }
28. catch (Exception e)
29. {
30. if(tx!=null)
31. {
32. tx.rollback();
33. }
34. }
35. finally
36. {
37. session.close();
38. }
39. }
40. }

```
public class Client
{
    public static void main(String[] args)
    {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        try
        {
            /*开启一个事务*/
            tx = session.beginTransaction();
            /*从数据库中获取id="402881e534fa5a440134fa5a45340002"的Customer对象*/
            Customer customer1 = (Customer)session.get(Customer.class, "402881e534fa5a440134fa5a45340002");
            System.out.println("customer.getUsername is"+customer1.getUsername());
            /*事务提交*/
            tx.commit();
            
            System.out.println("-------------------------------------");
            
            /*开启一个新事务*/
            tx = session.beginTransaction();
            /*从数据库中获取id="402881e534fa5a440134fa5a45340002"的Customer对象*/
            Customer customer2 = (Customer)session.get(Customer.class, "402881e534fa5a440134fa5a45340002");
            System.out.println("customer2.getUsername is"+customer2.getUsername());
            /*事务提交*/
            tx.commit();
            
            System.out.println("-------------------------------------");
            
            /*比较两个get()方法获取的对象是否是同一个对象*/
            System.out.println("customer1 == customer2 result is "+(customer1==customer2));
        }
        catch (Exception e)
        {
            if(tx!=null)
            {
                tx.rollback();
            }
        }
        finally
        {
            session.close();
        }
    }
}
```

Java代码 [![复制代码](http://itxiaojiang.iteye.com/images/icon_copy.gif)](http://itxiaojiang.iteye.com/blog/2240654 "复制代码") [![收藏代码](http://itxiaojiang.iteye.com/images/icon_star.png)![](http://itxiaojiang.iteye.com/images/spinner.gif)]()

01. 结果
02. Hibernate:
03. select
04. customer0\_.id as id0\_0\_,
05. customer0\_.username as username0\_0\_,
06. customer0\_.balance as balance0\_0_
07. from
08. customer customer0_
09. where
10. customer0\_.id=?
11. customer.getUsername islisi
12. \-------------------------------------
13. customer2.getUsername islisi
14. \-------------------------------------
15. customer1 == customer2 result is true

```
结果
Hibernate: 
    select
        customer0_.id as id0_0_,
        customer0_.username as username0_0_,
        customer0_.balance as balance0_0_ 
    from
        customer customer0_ 
    where
        customer0_.id=?
customer.getUsername islisi
-------------------------------------
customer2.getUsername islisi
-------------------------------------
customer1 == customer2 result is true
```

输出结果中只包含了一条SELECT SQL语句，而且customer1 == customer2 result is true说明两个取出来的对象是同一个对象。其原理是：第一次调用get()方法， Hibernate先检索缓存中是否有该查找对象，发现没有，Hibernate发送SELECT语句到数据库中取出相应的对象，然后将该对象放入缓存中，以便下次使用，第二次调用get()方法，Hibernate先检索缓存中是否有该查找对象，发现正好有该查找对象，就从缓存中取出来，不再去数据库中检索。

***5.3 二级缓存的管理：***

**evict(Class arg0, Serializable arg1)：**将某个类的指定ID的持久化对象从二级缓存中清除,释放对象所占用的资源。sessionFactory.evict(Customer.class, new Integer(1));

**evict(Class arg0)：**将指定类的所有持久化对象从二级缓存中清除,释放其占用的内存资源。sessionFactory.evict(Customer.class); 

**evictCollection(String arg0)：**将指定类的所有持久化对象的指定集合从二级缓存中清除,释放其占用的内存资源。sessionFactory.evictCollection("Customer.orders");

***5.4 二级缓存的配置***

Java代码 [![复制代码](http://itxiaojiang.iteye.com/images/icon_copy.gif)](http://itxiaojiang.iteye.com/blog/2240654 "复制代码") [![收藏代码](http://itxiaojiang.iteye.com/images/icon_star.png)![](http://itxiaojiang.iteye.com/images/spinner.gif)]()

01. 常用的二级缓存插件
02. EHCache  org.hibernate.cache.EhCacheProvider
03. OSCache  org.hibernate.cache.OSCacheProvider
04. SwarmCahe  org.hibernate.cache.SwarmCacheProvider
05. JBossCache  org.hibernate.cache.TreeCacheProvider
06. &lt;!-- EHCache的配置,hibernate.cfg.xml --&gt;
07. &lt;hibernate-configuration&gt;
08. &lt;session-factory&gt;
09. &lt;!-- 设置二级缓存插件EHCache的Provider类--&gt;
10. &lt;property name="hibernate.cache.provider\_class"&gt;
11. org.hibernate.cache.EhCacheProvider
12. &lt;/property&gt;
13. &lt;!-- 启动"查询缓存" --&gt;
14. &lt;property name="hibernate.cache.use\_query\_cache"&gt;
15. true
16. &lt;/property&gt;
17. &lt;/session-factory&gt;
18. &lt;/hibernate-configuration&gt;
19. &lt;!-- ehcache.xml --&gt;
20. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
21. &lt;ehcache&gt;
22. &lt;!--
23. 缓存到硬盘的路径
24. --&gt;
25. &lt;diskStore path="d:/ehcache"&gt;&lt;/diskStore&gt;
26. &lt;!--
27. 默认设置
28. maxElementsInMemory : 在內存中最大緩存的对象数量。
29. eternal : 缓存的对象是否永远不变。
30. timeToIdleSeconds ：可以操作对象的时间。
31. timeToLiveSeconds ：缓存中对象的生命周期，时间到后查询数据会从数据库中读取。
32. overflowToDisk ：内存满了，是否要缓存到硬盘。
33. --&gt;
34. &lt;defaultCache maxElementsInMemory="200" eternal="false"
35. timeToIdleSeconds="50" timeToLiveSeconds="60" overflowToDisk="true"&gt;&lt;/defaultCache&gt;
36. &lt;!--
37. 指定缓存的对象。
38. 下面出现的的属性覆盖上面出现的，没出现的继承上面的。
39. --&gt;
40. &lt;cache name="com.suxiaolei.hibernate.pojos.Order" maxElementsInMemory="200" eternal="false"
41. timeToIdleSeconds="50" timeToLiveSeconds="60" overflowToDisk="true"&gt;&lt;/cache&gt;
42. &lt;/ehcache&gt;
43. &lt;!-- \*.hbm.xml --&gt;
44. &lt;?xml version="1.0" encoding='UTF-8'?&gt;
45. &lt;!DOCTYPE hibernate-mapping PUBLIC
46. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
47. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" &gt;
48. &lt;hibernate-mapping&gt;
49. &lt;class&gt;
50. &lt;!-- 设置该持久化类的二级缓存并发访问策略 read-only read-write nonstrict-read-write transactional--&gt;
51. &lt;cache usage="read-write"/&gt;
52. &lt;/class&gt;
53. &lt;/hibernate-mapping&gt;

```
常用的二级缓存插件

EHCache  org.hibernate.cache.EhCacheProvider
OSCache  org.hibernate.cache.OSCacheProvider
SwarmCahe  org.hibernate.cache.SwarmCacheProvider
JBossCache  org.hibernate.cache.TreeCacheProvider

<!-- EHCache的配置,hibernate.cfg.xml --> 
<hibernate-configuration>
    <session-factory>
       <!-- 设置二级缓存插件EHCache的Provider类-->
       <property name="hibernate.cache.provider_class">
          org.hibernate.cache.EhCacheProvider
       </property>
       <!-- 启动"查询缓存" -->
       <property name="hibernate.cache.use_query_cache">
          true
       </property>
    </session-factory>
  </hibernate-configuration>


<!-- ehcache.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <!--
        缓存到硬盘的路径
    -->
    <diskStore path="d:/ehcache"></diskStore>
    <!--
        默认设置
        maxElementsInMemory : 在內存中最大緩存的对象数量。
        eternal : 缓存的对象是否永远不变。
        timeToIdleSeconds ：可以操作对象的时间。
        timeToLiveSeconds ：缓存中对象的生命周期，时间到后查询数据会从数据库中读取。
        overflowToDisk ：内存满了，是否要缓存到硬盘。
    -->
    <defaultCache maxElementsInMemory="200" eternal="false" 
        timeToIdleSeconds="50" timeToLiveSeconds="60" overflowToDisk="true"></defaultCache>
    <!--
        指定缓存的对象。
        下面出现的的属性覆盖上面出现的，没出现的继承上面的。
    -->
    <cache name="com.suxiaolei.hibernate.pojos.Order" maxElementsInMemory="200" eternal="false" 
        timeToIdleSeconds="50" timeToLiveSeconds="60" overflowToDisk="true"></cache>
</ehcache>


<!-- *.hbm.xml -->
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
   <class>
       <!-- 设置该持久化类的二级缓存并发访问策略 read-only read-write nonstrict-read-write transactional-->
       <cache usage="read-write"/>    
   </class>
</hibernate-mapping>

```

若存在一对多的关系，想要在在获取一方的时候将关联的多方缓存起来，需要在集合属性下添加&lt;cache&gt;子标签，这里需要将关联的对象的hbm文件中必须在存在&lt;class&gt;标签下也添加&lt;cache&gt;标签，不然Hibernate只会缓存OID。

Java代码 [![复制代码](http://itxiaojiang.iteye.com/images/icon_copy.gif)](http://itxiaojiang.iteye.com/blog/2240654 "复制代码") [![收藏代码](http://itxiaojiang.iteye.com/images/icon_star.png)![](http://itxiaojiang.iteye.com/images/spinner.gif)]()

01. &lt;hibernate-mapping&gt;
02. &lt;class name="com.suxiaolei.hibernate.pojos.Customer" table="customer"&gt;
03. &lt;!-- 主键设置 --&gt;
04. &lt;id name="id" type="string"&gt;
05. &lt;column name="id"&gt;&lt;/column&gt;
06. &lt;generator class="uuid"&gt;&lt;/generator&gt;
07. &lt;/id&gt;
08. &lt;!-- 属性设置 --&gt;
09. &lt;property name="username" column="username" type="string"&gt;&lt;/property&gt;
10. &lt;property name="balance" column="balance" type="integer"&gt;&lt;/property&gt;
11. &lt;set name="orders" inverse="true" cascade="all" lazy="false" fetch="join"&gt;
12. &lt;cache usage="read-only"/&gt;
13. &lt;key column="customer\_id" &gt;&lt;/key&gt;
14. &lt;one-to-many class="com.suxiaolei.hibernate.pojos.Order"/&gt;
15. &lt;/set&gt;
16. &lt;/class&gt;
17. &lt;/hibernate-mapping&gt;