Hibernate 二级缓存举例(4.2 Final版)
Hibernate 4.2里面的缓存
1、hibernate里面的缓存分成一级缓存与二级缓存与查询缓存
- 一级缓存:Session级别的缓存
- 二级缓存:SessionFactory级别的缓存
- 查询缓存
2、一级缓存
@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的缓存
3、二级缓存(在Hibernate里面使用二级缓存)
(一)导入相应的Jar包
- ehcache-core-2.4.3.jar
- hibernate-ehcache-4.2.0.Final.jar
- slf4j-api-1.6.1.jar
(二)打开缓存设置,并以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(); }
4、查询缓存
- 设置查询缓存,查询缓存是以二级缓存为基础<!--启用查询缓存-->
<propertyname="hibernate.cache.use_query_cache">true</property>
查询测试(必须使用setCacheable(true)方法)@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(); }
相关推荐
微微撒 2020-04-18
gwn00 2020-01-14
无情的你无情的雨 2020-07-18
dongxurr 2020-07-26
jimgreatly 2020-06-03
cnflat0 2020-04-25
技术驱动人生 2020-04-08
Justagreenonion 2020-03-27
zhiyuan0 2020-02-24
云之飞踢 2020-01-28
明月清风精进不止 2020-01-07
Justagreenonion 2020-01-05
manbucy 2014-05-20
javamagicsun 2019-12-17
栖梧桐 2019-12-13
javamagicsun 2019-12-04
GechangLiu 2016-11-23
flydoging 2019-11-05
Ashes 2019-11-05