(一)Hibernate的二级缓存策略的一般过程如下: 
1) 条件查询的时候,总是发出一条select * from table_name where …. (选择所有字段)这样的SQL语句查询数据库,一次获得所有的数据对象。 
2) 把获得的所有数据对象根据ID放入到第二级缓存中。 
3) 当Hibernate根据ID访问数据对象的时候,首先从Session一级缓存中查;查不到,如果配置了二级缓存,那么从二级缓存中查;查不到,再查询数据库,把结果按照ID放入到缓存。 
4) 删除、更新、增加数据的时候,同时更新缓存。 
  Hibernate的二级缓存策略,是针对于ID查询的缓存策略,对于条件查询则毫无作用。为此,Hibernate提供了针对条件查询的Query Cache。 
(二)什么样的数据适合存放到第二级缓存中? 
1 很少被修改的数据 
2 不是很重要的数据,允许出现偶尔并发的数据 
3 不会被并发访问的数据 
4 参考数据,指的是供应用参考的常量数据,它的实例数目有限,它的实例会被许多其他类的实例引用,实例极少或者从来不会被修改。 
(三)不适合存放到第二级缓存的数据? 
1 经常被修改的数据 
2 财务数据,绝对不允许出现并发 
3 与其他应用共享的数据。 
实践部分:
1:导入ehcache-1.2.3.jar 到lib下。
2:导入ehcache.xml到src下。
3:修改要配置缓存的那个持久化类的对象关系映射文件:  注:<cache>应放置在<class/>后面,<id/>的前面。
4:在spring的配置文件中,hibernate部分加入xml 代码
<!-- 启用二级缓存,默认是(false)关闭的 --> 
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<!-- 设置查询缓存 如果不设置'查询缓存',那么hibernate只会缓存使用load()方法获得的单个持久化对象,
	如果想缓存使用 findall()、list()、Iterator()、createCriteria()、createQuery()等方法获得的数据结果集的话,
	就需要设置 hibernate.cache.use_query_cache true 才行 -->
<prop key="hibernate.cache.use_query_cache">true</prop>
 <!-- 指定缓存产品提供商 -->  
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> 
五:在DAO中,调用find方法查询之前,设置使用缓存 
HibernateTemplate hibernateTemplate=this.getHibernateTemplate();
hibernateTemplate.setCacheQueries(true);//启用二级缓存。
List<Area> list = hibernateTemplate.find("from Area");
hibernateTemplate.setCacheQueries(false);//关闭查询缓存。。。

  

相关文章:

  • 2020-11-12
  • 2021-08-15
  • 2022-12-23
  • 2021-11-29
  • 2022-12-23
  • 2021-07-07
  • 2021-07-24
  • 2021-09-16
猜你喜欢
  • 2022-12-23
  • 2021-10-04
  • 2021-10-28
  • 2022-12-23
  • 2021-08-04
  • 2021-09-03
相关资源
相似解决方案