hibernate的查询缓存

在hibernate的使用中,大家多数时间都在讨论一级缓存和二级缓存,而往往忽略了查询缓存。其实hibernate的查询缓存在使用过程中也起着同样重要的作用。hibernate的查询缓存是主要是针对普通属性结果集的缓存, 而对于实体对象的结果集只缓存id。在一级缓存,二级缓存和查询缓存都打开的情况下作查询操作时这样的:查询普通属性,会先到查询缓存中取,如果没有,则查询数据库;查询实体,会先到查询缓存中取id,如果有,则根据id到缓存(一级/二级)中取实体,如果缓存中取不到实体,再查询数据库。
 
    和一级/二级缓存不同,查询缓存的生命周期 ,是不确定的,当前关联的表发生改变时,查询缓存的生命周期结束。
 
     查询缓存的配置和使用也是很简单的:
         1>查询缓存的启用不但要在配置文件中进行配置
             <property name="hibernate.cache.use_query_cache">true</property>
         2>还要在程序中显示的进行启用
             query.setCacheable(true);

1>查询缓存的启用不但要在配置文件中进行配置 -------换成spring配置
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>/WEB-INF/config/jdbc.properties</value>
            </list>
        </property>
    </bean>
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClassName}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="autoCommitOnClose" value="true"/>
        <property name="checkoutTimeout" value="${cpool.checkoutTimeout}"/>
        <property name="initialPoolSize" value="${cpool.minPoolSize}"/>
        <property name="minPoolSize" value="${cpool.minPoolSize}"/>
        <property name="maxPoolSize" value="${cpool.maxPoolSize}"/>
        <property name="maxIdleTime" value="${cpool.maxIdleTime}"/>
        <property name="acquireIncrement" value="${cpool.acquireIncrement}"/>
        <property name="maxIdleTimeExcessConnections" value="${cpool.maxIdleTimeExcessConnections}"/>
    </bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>    
        <property name="mappingLocations">
            <list>
                <value>classpath*:/com/jeecms/core/entity/hbm/*.hbm.xml</value>
                <value>classpath*:/com/jeecms/cms/entity/main/hbm/*.hbm.xml</value>
                <value>classpath*:/com/jeecms/cms/entity/assist/hbm/*.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <value>
            hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
            hibernate.show_sql=false
            hibernate.format_sql=false
            hibernate.query.substitutions=true 1, false 0
            hibernate.jdbc.batch_size=20
            //查询缓存配置
            hibernate.cache.use_query_cache=true
            </value>
        </property>
        <property name="entityInterceptor">   
            <ref local="treeInterceptor"/>
        </property>
        <property name="cacheProvider">
            <ref local="cacheProvider"/>
        </property>
        <property name="lobHandler">
            <ref bean="lobHandler" />
        </property>
    </bean>

2>还要在程序中显示的进行启用
public List<CmsSite> getList(boolean cacheable) {
        String hql = "from CmsSite bean order by bean.id asc";
        return getSession().createQuery(hql).setCacheable(cacheable).list();
    }

 
1.实体类:
  Student.jsva
public class Student {
   private Integer id;
   private String name;
   //一系列的setter.getter方法
}
 
2.映射文件
  Student.hbm.xml
   < class name ="com.sxt.hibernate.cache.entity.Student" table ="sxt_hibernate_student" >
        
    <!-- 指定本类的对象使用二级缓存(这也可以放在hibernate.cfg.xml中统一指定) -->
    <!--
    <cache usage="read-only"/>
    
-->
     < id name ="id" length ="4" >
       < generator class ="native" > </ generator >
     </ id >
     < property name ="name" length ="10" > </ property >
   </ class >
 
3.hibernate配置文件:
  hibernate.cfg.xml
< hibernate-configuration >
   < session-factory >
     < property name ="hibernate.connection.url" >jdbc:oracle:thin:@localhost:1521:ORCL10 </ property >
     < property name ="hibernate.connection.driver_class" >oracle.jdbc.driver.OracleDriver </ property >
     < property name ="hibernate.connection.username" >scott </ property >
     < property name ="hibernate.connection.password" >yf123 </ property >
     < property name ="hibernate.dialect" >org.hibernate.dialect.Oracle9Dialect </ property >
     < property name ="hibernate.show_sql" >true </ property >
    
    <!-- 开启二级缓存,其实hibernate默认就是开启的,这里显示的指定一下 -->
     < property name ="hibernate.cache.use_second_level_cache" >true </ property >
    <!-- 指定二级缓存产品的提供商 -->
     < property name ="hibernate.cache.provider_class" >org.hibernate.cache.EhCacheProvider </ property >
    
    <!-- 启用查询缓存 -->
     < property name ="hibernate.cache.use_query_cache" >true </ property >
    
     < mapping resource ="com/sxt/hibernate/cache/entity/Student.hbm.xml" />
    
    <!-- 指定那些类使用二级缓存 -->
     < class-cache usage ="read-only" class ="com.sxt.hibernate.cache.entity.Student" />
   </ session-factory >
</ hibernate-configuration >
 
4.测试方法:
   public static void main(String[] args) {
    Session session = null;
    Transaction t = null;

    * //**
     * 开启查询缓存,关闭二级缓存, 开启一个session,分别调用query.list
     */

  //如果不用查询缓存的话,那两个都发出查询语句,这也是默认的情况.
  /*
    try {
      session = HibernateUtils.getSession();
      t = session.beginTransaction();
      Query query = session.createQuery("select s.name from Student s");
      //启用查询缓存    
      query.setCacheable(true);
      List<String> names = query.list();
      for (Iterator<String> it = names.iterator(); it.hasNext();) {
        String name = it.next();
        System.out.println(name);
      }
      System.out.println("================================");
      query = session.createQuery("select s.name from Student s");
      //启用查询缓存
      query.setCacheable(true);
      //没有发出查询语句,因为这里使用的查询缓存
      names = query.list();
      for (Iterator<String> it = names.iterator(); it.hasNext();) {
        String name = it.next();
        System.out.println(name);
      }
      t.commit();
    } catch (Exception e) {
      e.printStackTrace();
      t.rollback();
    } finally {
      HibernateUtils.closeSession(session);
    }
  }*/

    
/*  @SuppressWarnings("unchecked")
  public static void main(String[] args) {
    Session session = null;
    Transaction t = null;

    *//**
     * 开启查询缓存,关闭二级缓存, 开启两个session,分别调用query.list
     *//*
    //如果不用查询缓存的话,那两个都发出查询语句,这也是默认的情况.
    try {
      session = HibernateUtils.getSession();
      t = session.beginTransaction();
      Query query = session.createQuery("select s.name from Student s");
      //启用查询缓存    
      //query.setCacheable(true);
      List<String> names = query.list();
      for (Iterator<String> it = names.iterator(); it.hasNext();) {
        String name = it.next();
        System.out.println(name);
      }

      t.commit();
    } catch (Exception e) {
      e.printStackTrace();
      t.rollback();
    } finally {
      HibernateUtils.closeSession(session);
    }
    
    System.out.println("================================");
    
    try {
      session = HibernateUtils.getSession();
      t = session.beginTransaction();
      Query query = session.createQuery("select s.name from Student s");
      //启用查询缓存    
      //query.setCacheable(true);
      //不会发出查询语句,因为查询缓存和session无关.
      List<String> names = query.list();
      for (Iterator<String> it = names.iterator(); it.hasNext();) {
        String name = it.next();
        System.out.println(name);
      }
      t.commit();
    } catch (Exception e) {
      e.printStackTrace();
      t.rollback();
    } finally {
      HibernateUtils.closeSession(session);
    }
  }*/

    
/*  @SuppressWarnings("unchecked")
  public static void main(String[] args) {
    Session session = null;
    Transaction t = null;

    *//**
     * 开启查询缓存,关闭二级缓存, 开启两个session,分别调用query.iterate
     *//*
    //如果不用查询缓存的话,那两个都发出查询语句,这也是默认的情况.
    try {
      session = HibernateUtils.getSession();
      t = session.beginTransaction();
      Query query = session.createQuery("select s.name from Student s");
      //启用查询缓存    
      query.setCacheable(true);
      for (Iterator<String> it = query.iterate(); it.hasNext();) {
        String name = it.next();
        System.out.println(name);
      }
      t.commit();
    } catch (Exception e) {
      e.printStackTrace();
      t.rollback();
    } finally {
      HibernateUtils.closeSession(session);
    }
    
    System.out.println("================================");
    
    try {
      session = HibernateUtils.getSession();
      t = session.beginTransaction();
      Query query = session.createQuery("select s.name from Student s");
      //启用查询缓存    
      query.setCacheable(true);
      //会发出查询语句,因为query.iterate不使用查询缓存
      for (Iterator<String> it = query.iterate(); it.hasNext();) {
        String name = it.next();
        System.out.println(name);
      }
      t.commit();
    } catch (Exception e) {
      e.printStackTrace();
      t.rollback();
    } finally {
      HibernateUtils.closeSession(session);
    }
  }*/

    
/*    @SuppressWarnings("unchecked")
  public static void main(String[] args) {
    Session session = null;
    Transaction t = null;

    *//**
     * 关闭查询缓存,关闭二级缓存, 开启两个session,分别调用query.list查询实体对象
     *//*
    //如果不用查询缓存的话,那两个都发出查询语句,这也是默认的情况.
    try {
      session = HibernateUtils.getSession();
      t = session.beginTransaction();
      Query query = session.createQuery("select s from Student s");
      //启用查询缓存    
      //query.setCacheable(true);
      List<Student> students = query.list();
      for (Iterator<Student> it = students.iterator(); it.hasNext();) {
        Student s = it.next();
        System.out.println(s.getName());
      }
      t.commit();
    } catch (Exception e) {
      e.printStackTrace();
      t.rollback();
    } finally {
      HibernateUtils.closeSession(session);
    }
    
    System.out.println("================================");
    
    try {
      session = HibernateUtils.getSession();
      t = session.beginTransaction();
      Query query = session.createQuery("select s from Student s");
      //启用查询缓存    
      //query.setCacheable(true);
      //会发出查询语句,因为list默认每次都会发出sql语句
      List<Student> students = query.list();
      for (Iterator<Student> it = students.iterator(); it.hasNext();) {
        Student s = it.next();
        System.out.println(s.getName());
      }
      t.commit();
    } catch (Exception e) {
      e.printStackTrace();
      t.rollback();
    } finally {
      HibernateUtils.closeSession(session);
    }
  }*/

    
/*  @SuppressWarnings("unchecked")
  public static void main(String[] args) {
    Session session = null;
    Transaction t = null;

    *//**
     * 开启查询缓存,关闭二级缓存, 开启两个session,分别调用query.list查询实体对象
     *//*
    //如果不用查询缓存的话,那两个都发出查询语句,这也是默认的情况.
    try {
      session = HibernateUtils.getSession();
      t = session.beginTransaction();
      Query query = session.createQuery("select s from Student s");
      //启用查询缓存    
      query.setCacheable(true);
      List<Student> students = query.list();
      for (Iterator<Student> it = students.iterator(); it.hasNext();) {
        Student s = it.next();
        System.out.println(s.getName());
      }
      t.commit();
    } catch (Exception e) {
      e.printStackTrace();
      t.rollback();
    } finally {
      HibernateUtils.closeSession(session);
    }
    
    System.out.println("================================");
    
    try {
      session = HibernateUtils.getSession();
      t = session.beginTransaction();
      Query query = session.createQuery("select s from Student s");
      //启用查询缓存    
      query.setCacheable(true);
      //会发出根据id查询实体的n条查询语句,因为这种情况下,查询过程是这样的:
      // 在第一次执行list时,会把查询对象的id缓存到查询缓存里
      // 第二次执行list时, 会遍历查询缓存里的id到缓存里去找实体对象,由于这里没找到实体对象,
      //所以就发出n条查询语句到数据库中查询.
      List<Student> students = query.list();
      for (Iterator<Student> it = students.iterator(); it.hasNext();) {
        Student s = it.next();
        System.out.println(s.getName());
      }
      t.commit();
    } catch (Exception e) {
      e.printStackTrace();
      t.rollback();
    } finally {
      HibernateUtils.closeSession(session);
    }
  }*/

    
  @SuppressWarnings("unchecked")
  public static void main(String[] args) {
    Session session = null;
    Transaction t = null;

    /**
     * 开启查询缓存,开启二级缓存, 开启两个session,分别调用query.list查询实体对象
     */

    //如果不用查询缓存的话,那两个都发出查询语句,这也是默认的情况.
    try {
      session = HibernateUtils.getSession();
      t = session.beginTransaction();
      Query query = session.createQuery("select s from Student s");
      //启用查询缓存    
      query.setCacheable(true);
      List<Student> students = query.list();
      for (Iterator<Student> it = students.iterator(); it.hasNext();) {
        Student s = it.next();
        System.out.println(s.getName());
      }
      t.commit();
    } catch (Exception e) {
      e.printStackTrace();
      t.rollback();
    } finally {
      HibernateUtils.closeSession(session);
    }
    
    System.out.println("================================");
    
    try {
      session = HibernateUtils.getSession();
      t = session.beginTransaction();
      Query query = session.createQuery("select s from Student s");
      //启用查询缓存    
      query.setCacheable(true);
      //不会发出查询语句,因为这种情况下,查询过程是这样的:
      // 在第一次执行list时,会把查询对象的id缓存到查询缓存里
      // 第二次执行list时, 会遍历查询缓存里的id到缓存里去找实体对象,由于这里开启了二级缓存,可以找到目标实体对象,
      //所以就不会再发出n条查询语句.
      List<Student> students = query.list();
      for (Iterator<Student> it = students.iterator(); it.hasNext();) {
        Student s = it.next();
        System.out.println(s.getName());
      }
      t.commit();
    } catch (Exception e) {
      e.printStackTrace();
      t.rollback();
    } finally {
      HibernateUtils.closeSession(session);
    }
  }

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值