hibernate Cacheable
来源:互联网 发布:别人要我电脑mac地址 编辑:程序博客网 时间:2024/06/08 06:23
今天仔仔细细的看了一下Hibernate的缓存,并做了实例实践了一把。google一下,网上的教程、文章很多。
自己小结一下:
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);
}
((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" />
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.cache.use_query_cache" value="true" />
0 0
- hibernate Cacheable
- @Cacheable
- Hibernate配置错误(javax.persistence.Cacheable)
- hibernate学习笔记1(javax.persistence.Cacheable)
- Cacheable VS Non-Cacheable
- hibernate注解报错注解方式下报java.lang.UnsupportedOperationException: Clobs are not cacheable
- NoClassDefFoundError: javax/persistence/Cacheable
- JForum Cacheable接口
- javax.persistence.Cacheable
- spring @Cacheable的用法
- volatile and non-cacheable
- Spring-Redis Cacheable中文翻译
- Spring 3.1 中使用 @Cacheable
- @Cacheable、@CachePut和@CacheEvict介绍
- Spring @Cacheable 的key生成
- @Cacheable、@CachePut和@CacheEvict介绍
- @Cacheable 缓存注解的用法
- Spring @Cacheable 的key生成
- 找不到类 android...app.WindowDecorActionBar
- Android 颜色对照表
- [Android 性能优化系列]布局篇之减少你的界面层级
- c 字符操作函数
- 12种排序算法详解
- hibernate Cacheable
- tomcat实现https登录
- 几种等等概率抽样方法
- 辗转相除法
- hdu 检测赛 Problem C(状压dp)
- 聚合类
- nginx的http2.0性能太逆天了,HTTPS网站性能优化
- C语言面试题(1)
- erlang game