---
title: "hibernate中缓存机制"
author: "Jason__Chen"
date: "2010-10-22T11:40:31Z"
tags: []
categories: ["编程语言"]
slug: "hibernate"
draft: false
lastmod: "2010-10-22T11:40:31Z"
id: 791348
url: "https://jason--chen.iteye.com/blog/791348"
---

一级缓存、二级缓存和查询缓存
1 一级缓存是指session缓存，当同一个session查询相同数据时，可以直接去缓存中拿，但如果是不同session即使查询内容相同也得去重新查询数据库。
2 二级缓存是指sessionfactory缓存，可以跨越session存在，即使不同的session当查询相同内容可以直接从二级缓存中拿数据而不用去访问数据库。二级缓存需要借助外界工具
 ![](http://dl.iteye.com/upload/picture/pic/74512/c063ef33-67a6-3302-aa5a-16b457cb5099.jpg)
其中Type表示存储方式，Cluster Safe表示是否支持集群，Query Cache supported表示是否直接查询缓存。
2.1.	打开二级缓存的方法是在hibernate.cfg.xml中配置：
		<property name="cache.use_second_level_cache">true</property>
        <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider 			</property>
		然后将ehcache的jar包和commons-logging包放入项目中
2.2.	然后配置类，如果使用的是annotation的方式，则在@Entity下加上 
		@Cache(usage= CacheConcurrencyStrategy.READ_WRITE)
		如果使用的是配置xml的方式，则在对应的hbm.xml中Class下配置
		<cache usage="read-write"/>
		Cache的属性有三个
	   		usage="transactional|read-write|nonstrict-read-write|read-only"    		 				region="RegionName"                                                 			include="all|non-lazy"
		usage（必选）说明了缓存的策略: transactional、 read-write、 nonstrict-read-write或 read-only一般使用的是read-write
		region(可选, 默认为类或者集合的名字(class or collection role name))指定第二级缓存的区域名(name of the second level cache region)
		include(可选,默认为 all)non-lazy 当属性级延迟抓取打开2.3.	关于二级缓存的使用：load,iterator默认使用二级缓存，list默认往二级缓存中存数据，但查询的时候不适用二级缓存，如果希望查询的时候也使用缓存则可以使用“查询缓存” ：使用的方法是在hibernate.cfg.xml中加入
<property name="cache.use_query_cache">true</property>
然后在query对象后加setCacheable(true)如：
			List<Husband> list1 = (List<Husband>)session1.createQuery("from 		Husband").setCacheable(true).list();