在hibernate的使用中,大家多數時間都在討論一級快取和二級快取,而往往忽略了查詢快取。其實hibernate的查詢快取在使用過程中也起著同樣重要的作用。hibernate的查詢快取是主要是針對普通屬性結果集的快取, 而對於實體物件的結果集只快取id。在一級快取,二級快取和查詢快取都開啟的情況下作查詢操作時這樣的:查詢普通屬性,會先到查詢快取中取,如果沒有,則查詢資料庫;查詢實體,會先到查詢快取中取id,如果有,則根據id到快取(一級/二級)中取實體,如果快取中取不到實體,再查詢資料庫。
 
    和一級/二級快取不同,查詢快取的生命週期 ,是不確定的,當前關聯的表發生改變時,查詢快取的生命週期結束。
 
     查詢快取的配置和使用也是很簡單的:
         1>查詢快取的啟用不但要在配置檔案中進行配置
             <property name=”hibernate.cache.use_query_cache”>true</property>
         2>還要在程式中顯示的進行啟用
             query.setCacheable(true);
 
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);
    }
  }