廉颇老矣,尚能饭否

java:从技术到管理

常用链接

统计

最新评论

Hibernate缓存配置 【转载】

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" />


柳德才
13691193654
18942949207
QQ:422157370
liudecai_zan@126.com
湖北-武汉-江夏-庙山

posted on 2009-04-08 15:43 liudecai_zan@126.com 阅读(169) 评论(0)  编辑  收藏 所属分类: 程序人生


只有注册用户登录后才能发表评论。


网站导航: