---
title: "Hibernate缓存"
author: "pure1202"
date: "2010-09-28T13:53:38Z"
tags: ["Cache", "EJB", "Hibernate", "JPA", "框架"]
categories: ["企业架构"]
slug: "hibernate"
draft: false
lastmod: "2010-09-28T13:54:44Z"
id: 774054
url: "https://aijof.iteye.com/blog/774054"
---

Hibernate缓存配置

____________________________________________________________________


```java

Hibernate的缓存分为：
　　一级缓存：在Session级别的，在Session关闭的时候，一级缓存就失效了。
　　二级缓存：在SessionFactory级别的，它可以使用不同的缓存实现，如EhCache、JBossCache、OsCache等。　

缓存的注释写法如下，加在Entity的java类上：
　　@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)　　

缓存的方式有四种，分别为：
　　CacheConcurrencyStrategy.NONE
　　CacheConcurrencyStrategy.READ_ONLY，只读模式，在此模式下，如果对数据进行更新操作，会有异常；
　　CacheConcurrencyStrategy.READ_WRITE，读写模式在更新缓存的时候会把缓存里面的数据换成一个锁，其它事务如果去取相应的缓存数据，发现被锁了，直接就去数据库查询；
　　CacheConcurrencyStrategy.NONSTRICT_READ_WRITE，不严格的读写模式则不会的缓存数据加锁；
　　CacheConcurrencyStrategy.TRANSACTIONAL，事务模式指缓存支持事务，当事务回滚时，缓存也能回滚，只支持JTA环境。

另外还有如下注意事项：
　　1、查询缓存需要在Query的相应方法执行前加上这么一句：　　       
    query.setCacheable(true);
　　在使用Hibernate时，获得的query有setCacheable方法，可以设置使用缓存，但当使用JPA时，javax.persistence.Query并没有setCacheable方法，此时如果JPA的实现是Hibernate时，可以将其进行如下转化，再调用setCacheable方法（如果JPA的实现是其它ORMAP框架，就不知道怎么做了）。
if　(query　instanceof　org.hibernate.ejb.QueryImpl)　{
　　　 ((org.hibernate.ejb.QueryImpl)　query).getHibernateQuery().setCacheable(true);
}
　　2、还有就是查询缓存的查询执行后，会将查询结果放入二级缓存中，但是放入的形式是以ID为Key，实例作为一个Value。
　　3、hibernate的配置文件中需加入如下信息：
<property　name="hibernate.cache.provider_class"　value="org.hibernate.cache.EhCacheProvider"　/>
<property　name="hibernate.cache.use_second_level_cache"　value="true"　/>
<property　name="hibernate.cache.use_query_cache"　value="true"　/>

```
 

吴越泛舟·荡漾心情