Home  >  Article  >  Database  >  关于Hibernate缓存,想要最新数据连session.clear都麻烦

关于Hibernate缓存,想要最新数据连session.clear都麻烦

WBOY
WBOYOriginal
2016-06-07 15:21:44979browse

关于Hibernate缓存,想要最新数据连session.clear都麻烦

一、hibernate一级缓存
(1)hibernate支持两个级别的缓存,默认只支持一级缓存;
(2)每个Session内部自带一个一级缓存;
(3)某个Session被关闭时,其对应的一级缓存自动清除;
(4)save、update、saveOrupdate、load、get、list、iterate、lock方法都会向缓存中存对象.
(5)可以从缓存中读数据的只有: get、load、iterate
(6)Query对象默认情况下不读缓存,如果要使其支持缓存,则要通过语法:
query.setCacheable(true);
true
(7)打开query缓存后,只有查询条件与以前的查询完全相同时,才会在缓存中匹配成功.
(8)Criteria对缓存支持不足;
(9)一级缓存不能控制缓存中的对象数量,要注意大批量操作数据时可能造成的内存溢出,可以利用清除缓存.

session.clear() 清除缓存中所有对象 session.evict(user) 清除指定对象

我已经试过了,session.clear()能清掉session.createQuery,但是清不掉session.createSQLQuery。
session.createSQLQuery是谁都清不掉,以下方法我都试过了,没有一个好使的,数据照样是错的,不是数据库最新数据:

session.setFlushMode(FlushMode.AUTO); session.setCacheMode(CacheMode.NORMAL); session.flush(); session.clear(); sqlQuery.setCacheable(false);

唯一能清掉的方法是关闭session。。。无语,hibernate难道是SB,还是我是SB不会用?难道还有专门清理session.createSQLQuery的缓存的?这种缓存清不掉是BUG吗?

二、hibernate二级缓存

save、update、saveOrupdate、loadget、list、query、Criteria方法都会填充二级缓存 getload、iterate会从二级缓存中取数据 session.save(user) 如果user主键使用“native”生成,则不放入二级缓存.

(1)开启二级缓存

property name="cache.use_second_level_cache">trueproperty>

(2)为hibernate指定二级缓存的实现类

"cache.provider_class"> org

(3)为OSCache缓存创建配置文件(需要hibernate_Advance_Surpport_lib)
src/oscache.properties
修改配置中的:
cache.capacity=1000 指定缓存可以容纳多少对象

(4)指明哪些类需要放入二级缓存,,需要长期使用到的对象才有必要放入二级缓存

class-cache class="entity.PetInfo" usage="read-only" /> //不允许更新缓存中的对象 class-cache class="entity.PetInfo" usage="read-write" /> //允许更新缓存中的对象

或在orm文件中:

"entity.PetInfo" table="PetInfo" schema="dbo" catalog="epet"> "read-only"/> ...

(5)如果需要清除二级缓存,使用下面语法

sessionFactory.evict(User.class) 清除所有user

Hibernate学习入门教程 

在Hibernate中开启日志

Hibernate+JUnit测试实体类生成数据库表 

Hibernate整体理解

Hibernate的映射机制 

Hibernate 的详细介绍:请点这里
Hibernate 的下载地址:请点这里

本文永久更新链接地址

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn