logo
 
 
|
|
|
|
|
|
|
|
 
 
您的位置:首页 - 专业知识
Hibernate中二级缓存使用教学(1)
[2010-04-16]

Hibernate中,二级缓存在Hibernate中对应的即SessionFactory范围的缓存,是进程缓存或集群缓存,二级缓存在Hibernate中是可以配置的,可以通过在hibernate.cfg.xml来如下来指定二级缓存。
1. 打开hibernate的二级缓存
<property name="cache.use_second_level_cache">true</property>
2.指定第三方二级缓存框架为EhCache
<property name="cache.provider_class">
  org.hibernate.cache.EhCacheProvider
 </property>
3.打开查询缓存
<property name="cache.use_query_cache">true</property>

为了让学员们更好地理解各个查询方法与二级缓存的关系,我在教学过程中使用了如下的一些示例来给与说明:

先写统计分析二级缓存的方法
//测试统计分析二级缓存或查询缓存的内容
 public void testSecondLevelStatistics(String regionName){
  Map<Object,Object> map=HibernateSessionFactory.getSessionFactory()
    .getStatistics()
      .getSecondLevelCacheStatistics(regionName)
         .getEntries();
  System.out.println("开始遍历键");
  for(Object object: map.keySet()){
    System.out.println(object);
  }
  System.out.println();
  System.out.println("开始遍历值");
  for(Object object: map.values()){
    System.out.println(object);
  }
 }

该方法说明如下:该方法返回Map,得到缓存的键的Set,及缓存的对象的Set。然后我们在控制台下输出,以确定到底有没有缓存,以及缓存的键与值分别是什么,便于学员们更好地理解二级缓存。

先看第一个我们常用的查询方法:get

/测试get方法的二级缓存
 public void testCacheByGet(){
  Session session=super.getSession();
  //设置session如何与二级缓存交互,默认为normal
  session.setCacheMode(CacheMode.GET);
  Fwxx fwxx=(Fwxx)session.get(Fwxx.class ,1);
  System.out.println("第一次输出:"+fwxx.getLxr());
  super.closeSession();
  System.out.println();
  
  testSecondLevelStatistics("com.jc.mysql.entity.Fwxx");
  try {
   Thread.sleep(5000);
  } catch (InterruptedException e){
   e.printStackTrace();
  }
  fwxx=(Fwxx)super.get(1,Fwxx.class);
  System.out.println("第二次输出:"+fwxx.getLxr());
  
 }
 
 //测试load方法的二级缓存
 public void testCacheByLoad(){
  Session session=super.getSession();
  session.setCacheMode(CacheMode.PUT);
  Fwxx fwxx=(Fwxx)session.load(Fwxx.class,1);
  System.out.println("第一次输出:"+fwxx.getId());
  super.closeSession();
  System.out.println();
  
  testSecondLevelStatistics("com.jc.mysql.entity.Fwxx");
  HibernateSessionFactory.getSessionFactory()
     .evict(Fwxx.class, 1);
  try {
   Thread.sleep(5000);
  } catch (InterruptedException e){
   e.printStackTrace();
  }
  //session=super.getSession();
  //fwxx=(Fwxx)session.load(Fwxx.class,1);
  System.out.println("第二次输出:"+fwxx.getTel());
  
 }

上一篇:Rss文件格式及其应用
下一篇:Hibernate中获取数据方式与缓存使用
   
Hibernate中获取数据方式与缓存使用 Hibernate中获取数据方式与缓存使用
DisplayTag展示与Hibernate物理分页(连载3) DisplayTag展示与Hibernate物理分页(连载3)
DisplayTag展示与Hibernate物理分页(连载2) DisplayTag展示与Hibernate物理分页(连载2)
QTP输出值的另一种使用 QTP输出值的另一种使用
 

在线报名

  • 姓       名:*
  • 高考成绩:*
  • 电       话:*
  • 地       址:*
 
课程咨询
 

 
中博教育客服在线
 
©南京北大青鸟 隐私政策
学费咨询
学历咨询
专业咨询
订座试听
就业咨询
课程咨询
测试认证
软件认证