Hibernate 二级缓存举例(4.2 Final版)

[align=center][b]Hibernate 4.2里面的缓存[/b][/align]
[b]1、 hibernate 里面的缓存分成一级缓存与二级缓存与查询缓存[/b]
[list]
[*]一级缓存:Session级别的缓存
[*]二级缓存:SessionFactory级别的缓存
[*]查询缓存
[/list]
[b]2、 一级缓存[/b]
@Test
public void testCache() {
Session s = sf.getCurrentSession();
s.beginTransaction();
Category c = (Category)s.load(Category.class, 1);
System.out.println(c.getName());

Category c1 = (Category)s.load(Category.class, 1);
System.out.println(c1.getName());

s.getTransaction().commit();

Session s2 = sf.getCurrentSession();
s2.beginTransaction();
Category c2 = (Category)s2.load(Category.class, 1);
System.out.println(c2.getName());
s2.getTransaction().commit();
}

在不使用二级缓存的情况下,如果在一个Session里面对一个对象进行Load两次,那么只查询一次,如果在不同的Session里面各Load一次,会进行两次查询,也就是第二个Session不能访问第一个Session的缓存
[b]3、 二级缓存(在Hibernate里面使用二级缓存)[/b]
(一) 导入相应的Jar包
[list]
[*]ehcache-core-2.4.3.jar
[*]hibernate-ehcache-4.2.0.Final.jar
[*]slf4j-api-1.6.1.jar
[/list]
(二) 打开缓存设置,并以EhCache为例子进行实验
<property name="hibernate.cache.use_second_level_cache">true</property>  
<property name="cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

(三) 设置缓存对象,在Category类上面加上注解@Cache
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
public class Category {

(四) 对二级缓存进行测试,此时在两个不同的Session里面进行Load也只会查询一次
@Test
public void testCache2() {
Session s = sf.getCurrentSession();
s.beginTransaction();
Category c = (Category)s.load(Category.class, 1);
System.out.println(c.getName());
s.getTransaction().commit();

Session s2 = sf.getCurrentSession();
s2.beginTransaction();
Category c2 = (Category)s2.load(Category.class, 1);
System.out.println(c2.getName());
s2.getTransaction().commit();
}


[b]4、 查询缓存[/b]
[list]
[*]设置查询缓存,查询缓存是以二级缓存为基础
<!-- 启用查询缓存 -->
<property name="hibernate.cache.use_query_cache">true</property>
[*]查询测试(必须使用setCacheable(true)方法)
[/list]
@Test
public void testQueryCache() {
Session s = sf.getCurrentSession();
s.beginTransaction();
List<Category> cs = (List<Category>)s.createQuery("from Category").setCacheable(true).list();
for(Category c : cs) {
System.out.println(c.getName());
}

List<Category> cs2 = (List<Category>)s.createQuery("from Category").setCacheable(true).list();
for(Category c : cs2) {
System.out.println(c.getName());
}
s.getTransaction().commit();

Session s2 = sf.getCurrentSession();
s2.beginTransaction();
List<Category> cs3 = (List<Category>)s2.createQuery("from Category").setCacheable(true).list();
for(Category c : cs3) {
System.out.println(c.getName());
}
s2.getTransaction().commit();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值