欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate+EhCache配置二级缓存

程序员文章站 2022-05-05 12:59:40
...

FROM:  http://sjsky.iteye.com/blog/1312132

本文主要讲一讲Hibernate+EhCache配置二级缓存的基本使用方法,主要分以下两个方面介绍:

 

(有关EhCache的基础介绍可参见:http://sjsky.iteye.com/blog/1288257 )

  • Cache的多种配置方法
  • Hibernate+EhCache集成demo

[一]、Cache的多种配置方法

       Javabean cache的配置有三种,下面将一一介绍,具体如下::

        (1).bean中注解配置的方式: @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

        (2).hibernate.cfg.xml中标签配置方式: <class-cache class="" usage="" />

        (3).映射文件*.hb.xml中标签配置方式: <cache usage=" />

 

      1. classpath:ehcahce.xml配置文件如下:

 

Xml代码   Hibernate+EhCache配置二级缓存
            
    
    博客分类: 待看文章Hibernate  
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.          xsi:noNamespaceSchemaLocation="ehcache.xsd"  
  4.          updateCheck="true" monitoring="autodetect"  
  5.          dynamicConfig="true">  
  6.   
  7.     <diskStore path="java.io.tmpdir"/>  
  8.   
  9.     <transactionManagerLookup class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup"  
  10.                               properties="jndiName=java:/TransactionManager" propertySeparator=";"/>  
  11.   
  12.     <cacheManagerEventListenerFactory class="" properties=""/>  
  13.   
  14.     <defaultCache  
  15.             maxElementsInMemory="100"  
  16.             eternal="false"  
  17.             timeToIdleSeconds="120"  
  18.             timeToLiveSeconds="120"  
  19.             overflowToDisk="true"  
  20.             diskSpoolBufferSizeMB="30"  
  21.             maxElementsOnDisk="100"  
  22.             diskPersistent="false"  
  23.             diskExpiryThreadIntervalSeconds="120"  
  24.             memoryStoreEvictionPolicy="LRU"  
  25.             statistics="false"  
  26.             />  
  27.   
  28.     <cache name="org.hibernate.cache.StandardQueryCache"  
  29.         maxElementsInMemory="5"   
  30.         eternal="false"   
  31.         timeToLiveSeconds="120"  
  32.         overflowToDisk="true" />  
  33.   
  34.     <cache name="org.hibernate.cache.UpdateTimestampsCache"  
  35.         maxElementsInMemory="5000"   
  36.         eternal="true"   
  37.         overflowToDisk="true" />  
  38.   
  39.     <cache name="sampleCache1"  
  40.            maxElementsInMemory="10000"  
  41.            maxElementsOnDisk="1000"  
  42.            eternal="false"  
  43.            overflowToDisk="true"  
  44.            diskSpoolBufferSizeMB="20"  
  45.            timeToIdleSeconds="300"  
  46.            timeToLiveSeconds="600"  
  47.            memoryStoreEvictionPolicy="LFU"  
  48.            transactionalMode="off"  
  49.             />  
  50.   
  51.     <cache name="sampleCache2"  
  52.            maxElementsInMemory="1000"  
  53.            eternal="true"  
  54.            overflowToDisk="false"  
  55.            memoryStoreEvictionPolicy="FIFO"  
  56.             />  
  57. </ehcache>  

    2.hibernate配置文件:hibernate.cfg.xml

Xml代码   Hibernate+EhCache配置二级缓存
            
    
    博客分类: 待看文章Hibernate  
  1. <!DOCTYPE hibernate-configuration  
  2.     PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"  
  3.     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  4.   
  5. <hibernate-configuration>  
  6.   
  7.     <session-factory>  
  8.         <property name="connection.driver_class">  
  9.             oracle.jdbc.driver.OracleDriver  
  10.         </property>  
  11.         <property name="connection.url">  
  12.             jdbc:oracle:thin:@localhost:1521:ora11g  
  13.         </property>  
  14.         <property name="connection.username">mytest</property>  
  15.         <property name="connection.password">111111</property>  
  16.   
  17.         <property name="dialect">  
  18.             org.hibernate.dialect.Oracle9Dialect  
  19.         </property>  
  20.   
  21.         <property name="connection.useUnicode">true</property>  
  22.         <property name="connection.characterEncoding">UTF-8</property>  
  23.         <property name="connection.SetBigStringTryClob">true</property>  
  24.         <property name="connection.pool_size">10</property>  
  25.         <property name="hibernate.jdbc.batch_size">10</property>  
  26.   
  27.   
  28.         <property name="show_sql">true</property>  
  29.         <property name="format_sql">false</property>  
  30.         <property name="current_session_context_class">thread</property>  
  31.         <property name="hbm2ddl.auto">update</property>  
  32.         <!--  Hibernate 3.3 and higher -->  
  33.         <!--  
  34.         <property name="hibernate.cache.region.factory_class">  
  35.             net.sf.ehcache.hibernate.EhCacheRegionFactory  
  36.         </property>  
  37.         <property name="hibernate.cache.region.factory_class">  
  38.             net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory  
  39.         </property>  
  40.         -->  
  41.         <!-- hibernate3.0-3.2 cache config-->  
  42.         <!--   
  43.         <property name="hibernate.cache.region.factory_class">  
  44.             net.sf.ehcache.hibernate.EhCacheProvider  
  45.         </property>  
  46.         -->  
  47.         <property name="hibernate.cache.provider_class">  
  48.             net.sf.ehcache.hibernate.SingletonEhCacheProvider  
  49.         </property>  
  50.           
  51.         <!-- Enable Second-Level Cache and Query Cache Settings -->  
  52.         <property name="hibernate.cache.use_second_level_cache">  
  53.             true  
  54.         </property>  
  55.         <property name="hibernate.cache.use_query_cache">  
  56.             true  
  57.         </property>  
  58.   
  59.         <!-- 注解配置  -->  
  60.         <mapping class="michael.cache.ehcache.hibernate.EhUserInfo" />  
  61.         <mapping class="michael.cache.ehcache.hibernate.EhBlogTopic" />  
  62.         <mapping class="michael.cache.ehcache.hibernate.EhBlogTopic2" />  
  63.   
  64.         <!-- 映射文件 -->  
  65.         <mapping  
  66.             resource="michael/cache/ehcache/hibernate/tb_EhBlogTopic3.hb.xml" />  
  67.   
  68.         <!-- class-cache config -->  
  69.         <class-cache class="michael.cache.ehcache.hibernate.EhBlogTopic"  
  70.             usage="read-write" />  
  71.   
  72.     </session-factory>  
  73. </hibernate-configuration>  

   3.相关javabean代码片段如下:

      (1).hibernate.cfg.xml中<calss-cache>标签配置的:EhBlogTopic.java:

Java代码   Hibernate+EhCache配置二级缓存
            
    
    博客分类: 待看文章Hibernate  
  1. /** 
  2.  * @blog http://sjsky.iteye.com 
  3.  * @author Michael 
  4.  */  
  5. @Entity  
  6. @Table(name = "MY_TB_EH_BLOG_TOPIC")  
  7. public class EhBlogTopic implements Serializable {  
  8.   
  9.     /** 
  10.      * serialVersionUID 
  11.      */  
  12.     private static final long serialVersionUID = -570936907944909799L;  
  13.   
  14.     private Integer id;  
  15.   
  16.     private String userId;  
  17.   
  18.     private String topic;  
  19.   
  20.     private String site;  
  21.   
  22.     //其他省略  
  23. }  

    (2). bean中注解的方式配置cache的:EhBlogTopic2.java

Java代码   Hibernate+EhCache配置二级缓存
            
    
    博客分类: 待看文章Hibernate  
  1. /** 
  2.  * @blog http://sjsky.iteye.com 
  3.  * @author Michael 
  4.  */  
  5. @Entity  
  6. @Table(name = "MY_TB_EH_BLOG_TOPIC2")  
  7. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
  8. public class EhBlogTopic2 implements Serializable {  
  9.       //属性和EhBlogTopic一样  
  10.      //其他省略  
  11. }  

    (3). 映射文件*.hb.xml中添加cache标签的: EhBlogTopic3.java

Java代码   Hibernate+EhCache配置二级缓存
            
    
    博客分类: 待看文章Hibernate  
  1. /** 
  2.  * @blog http://sjsky.iteye.com 
  3.  * @author Michael 
  4.  */  
  5. public class EhBlogTopic3 implements Serializable {  
  6.    //属性和EhBlogTopic一样  
  7.    //其他省略  
  8. }  

     tb_EhBlogTopic3.hb.xml

Xml代码   Hibernate+EhCache配置二级缓存
            
    
    博客分类: 待看文章Hibernate  
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC  
  3.     "-//Hibernate/Hibernate Mapping DTD 2.0//EN"  
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  5.   
  6. <hibernate-mapping package="michael.cache.ehcache.hibernate">  
  7.   
  8.     <class name="EhBlogTopic3" table="MY_TB_EH_BLOG_TOPIC3">  
  9.         <cache usage="read-write" />  
  10.         <id name="id" type="int" unsaved-value="null">  
  11.             <generator class="increment" />  
  12.         </id>  
  13.         <property name="userId" column="USER_ID" type="string"  
  14.             not-null="false" length="20" />  
  15.   
  16.         <property name="topic" column="TOPIC" type="string"  
  17.             not-null="false" length="100" />  
  18.         <property name="site" column="SITE" type="string"  
  19.             not-null="false" length="100" />  
  20.   
  21.     </class>  
  22. </hibernate-mapping>  

      (4). 没有配置cache的bean:EhUserInfo.java

Java代码   Hibernate+EhCache配置二级缓存
            
    
    博客分类: 待看文章Hibernate  
  1. /** 
  2.  * @blog http://sjsky.iteye.com 
  3.  * @author Michael 
  4.  */  
  5. @Entity  
  6. @Table(name = "MY_TB_EH_USER_INFO")  
  7. public class EhUserInfo implements Serializable {  
  8.   
  9.     /** 
  10.      * serialVersionUID 
  11.      */  
  12.     private static final long serialVersionUID = 930384253681679239L;  
  13.   
  14.     private Integer id;  
  15.   
  16.     private String userId;  
  17.   
  18.     private String userName;  
  19.   
  20.     private String otherInfo;  
  21.   
  22.     /** 
  23.      * @return the id 
  24.      */  
  25.     @Id  
  26.     @GeneratedValue  
  27.     @Column(name = "ID")  
  28.     public Integer getId() {  
  29.         return id;  
  30.     }  
  31.   
  32.   //其他省略。。。  
  33.   
  34. }  

 

   4.测试运行代码如下:

 

Java代码   Hibernate+EhCache配置二级缓存
            
    
    博客分类: 待看文章Hibernate  
  1. package michael.cache.ehcache.hibernate;  
  2.   
  3. import java.util.List;  
  4.   
  5. import michael.hibernate.bigstring.oracle.BigStrBlob;  
  6. import net.sf.ehcache.Cache;  
  7. import net.sf.ehcache.CacheManager;  
  8.   
  9. import org.hibernate.Query;  
  10. import org.hibernate.Session;  
  11. import org.hibernate.SessionFactory;  
  12. import org.hibernate.Transaction;  
  13. import org.hibernate.cfg.AnnotationConfiguration;  
  14. import org.hibernate.cfg.Configuration;  
  15.   
  16. /** 
  17.  *  
  18.  * @blog http://sjsky.iteye.com 
  19.  * @author Michael 
  20.  */  
  21. public class TestEhcacheHibernate {  
  22.   
  23.     /** 
  24.      * @param args 
  25.      */  
  26.     @SuppressWarnings("unchecked")  
  27.     public static void main(String[] args) {  
  28.         testMulitConfigMethod();  
  29.     }  
  30.   
  31.     /** 
  32.      * 测试多种配置缓存的方法 
  33.      */  
  34.     public static void testMulitConfigMethod() {  
  35.         SessionFactory sessionFactory = null;  
  36.         try {  
  37.             System.out.println("ehcache - hibernate Test ...");  
  38.             Configuration config = new AnnotationConfiguration()  
  39.                     .configure("michael/cache/ehcache/hibernate/hibernate.cfg.xml");  
  40.             System.out.println("hibernate config successful :" + config);  
  41.             sessionFactory = config.buildSessionFactory();  
  42.             Transaction ta = null;  
  43.             try {  
  44.                 Session session = sessionFactory.getCurrentSession();  
  45.                 ta = session.beginTransaction();  
  46.             } catch (Exception e) {  
  47.                 e.printStackTrace();  
  48.                 ta.rollback();  
  49.             }  
  50.             String[] cacheNames = CacheManager.getInstance().getCacheNames();  
  51.             System.out.println("缓存的key cacheNames length := "  
  52.                     + cacheNames.length + " 具体详细列表如下:");  
  53.             for (String name : cacheNames) {  
  54.                 System.out.println("name := " + name);  
  55.             }  
  56.         } catch (Exception e) {  
  57.             e.printStackTrace();  
  58.         }  
  59.         System.out.println("ehcache - hibernate Test end.");  
  60.     }  
  61. }  

 运行结果如下:

 

ehcache - hibernate Test ...
hibernate config successful :org.hibernate.cfg.AnnotationConfiguration@193c0cf
2011-12-15 11:32:36 net.sf.ehcache.hibernate.AbstractEhcacheProvider buildCache
警告: Could not find a specific ehcache configuration for cache named [michael.cache.ehcache.hibernate.EhBlogTopic]; using defaults.
2011-12-15 11:32:36 net.sf.ehcache.hibernate.AbstractEhcacheProvider buildCache
警告: Could not find a specific ehcache configuration for cache named [michael.cache.ehcache.hibernate.EhBlogTopic2]; using defaults.
2011-12-15 11:32:36 net.sf.ehcache.hibernate.AbstractEhcacheProvider buildCache
警告: Could not find a specific ehcache configuration for cache named [michael.cache.ehcache.hibernate.EhBlogTopic3]; using defaults.
2011-12-15 11:32:37 net.sf.ehcache.util.UpdateChecker doCheck
信息: New update(s) found: 2.4.6 [http://www.terracotta.org/confluence/display/release/Release+Notes+Ehcache+Core+2.4]. Please check http://ehcache.org for the latest version.
缓存的key cacheNames length := 7 具体详细列表如下:
name := sampleCache2
name := michael.cache.ehcache.hibernate.EhBlogTopic2 
name := org.hibernate.cache.UpdateTimestampsCache
name := sampleCache1
name := michael.cache.ehcache.hibernate.EhBlogTopic 
name := org.hibernate.cache.StandardQueryCache
name := michael.cache.ehcache.hibernate.EhBlogTopic3 
ehcache - hibernate Test end.

  从运行结果可见:三种方式的缓存配置都已经成功。

 

[二]、Hibernate+EhCache集成demo

      1.分别初始化EhUserInfo(没有配置cache的)和EhBlogTopic(配置过cache的)数据如下:

EhUserInfo:


Hibernate+EhCache配置二级缓存
            
    
    博客分类: 待看文章Hibernate  

  EhBlogTopic: 
Hibernate+EhCache配置二级缓存
            
    
    博客分类: 待看文章Hibernate  

   2.演示代码:

Java代码   Hibernate+EhCache配置二级缓存
            
    
    博客分类: 待看文章Hibernate  
  1. package michael.cache.ehcache.hibernate;  
  2.   
  3. import java.util.List;  
  4.   
  5. import michael.hibernate.bigstring.oracle.BigStrBlob;  
  6. import net.sf.ehcache.Cache;  
  7. import net.sf.ehcache.CacheManager;  
  8.   
  9. import org.hibernate.Query;  
  10. import org.hibernate.Session;  
  11. import org.hibernate.SessionFactory;  
  12. import org.hibernate.Transaction;  
  13. import org.hibernate.cfg.AnnotationConfiguration;  
  14. import org.hibernate.cfg.Configuration;  
  15.   
  16. /** 
  17.  *  
  18.  * @blog http://sjsky.iteye.com 
  19.  * @author Michael 
  20.  */  
  21. public class TestEhcacheHibernate {  
  22.   
  23.     /** 
  24.      * @param args 
  25.      */  
  26.     @SuppressWarnings("unchecked")  
  27.     public static void main(String[] args) {  
  28.         SessionFactory sessionFactory = null;  
  29.         try {  
  30.             System.out.println("ehcache - hibernate Test ...");  
  31.             Configuration config = new AnnotationConfiguration()  
  32.                     .configure("michael/cache/ehcache/hibernate/hibernate.cfg.xml");  
  33.   
  34.             sessionFactory = config.buildSessionFactory();  
  35.             System.out.println("buildSessionFactory===============");  
  36.   
  37.             System.out.println("====================================");  
  38.             System.out.println("session open ....");  
  39.             System.out.println("同一个session(一级缓存默认的)中,没有配置cache的Bean");  
  40.             Transaction ta = null;  
  41.             try {  
  42.                 Session session = sessionFactory.getCurrentSession();  
  43.                 String hsql = "select t from EhUserInfo t ";  
  44.                 ta = session.beginTransaction();  
  45.                 Query query = session.createQuery(hsql);  
  46.                 System.out.println("查询全部query.list().size:"  
  47.                         + query.list().size());  
  48.   
  49.                 System.out.println("再根据ID=1查询某记录时不会再去查数据库,故不会打印hsql");  
  50.                 EhUserInfo vo1 = (EhUserInfo) session.get(EhUserInfo.class1);  
  51.                 System.out.println("根据ID=1找到的记录:" + vo1);  
  52.                 ta.commit();  
  53.             } catch (Exception e) {  
  54.                 e.printStackTrace();  
  55.                 ta.rollback();  
  56.             }  
  57.             System.out.println("session closed.");  
  58.   
  59.             System.out.println("session open ....");  
  60.             try {  
  61.                 Session session = sessionFactory.getCurrentSession();  
  62.                 ta = session.beginTransaction();  
  63.                 System.out.println("第一次根据ID=1查询某记录时,会打印hsql");  
  64.                 EhUserInfo vo1 = (EhUserInfo) session.get(EhUserInfo.class1);  
  65.                 System.out.println("根据ID=1找到的记录:" + vo1);  
  66.                 ta.commit();  
  67.             } catch (Exception e) {  
  68.                 e.printStackTrace();  
  69.                 ta.rollback();  
  70.             }  
  71.             System.out.println("session closed.");  
  72.   
  73.             System.out.println("====================================");  
  74.             System.out.println("当前同一个sessionFactory,没有配置cache的Bean,");  
  75.             System.out.println("session open ....");  
  76.             try {  
  77.                 Session session = sessionFactory.getCurrentSession();  
  78.                 ta = session.beginTransaction();  
  79.                 System.out.println("第一次根据ID=1查询记录时会再去查数据库,故打印hsql如下:");  
  80.                 EhUserInfo vo1 = (EhUserInfo) session.get(EhUserInfo.class1);  
  81.                 System.out.println("根据ID=1找到的记录:" + vo1);  
  82.                 ta.commit();  
  83.             } catch (Exception e) {  
  84.                 e.printStackTrace();  
  85.                 ta.rollback();  
  86.             }  
  87.             System.out.println("session closed.");  
  88.             System.out.println("====================================");  
  89.             String[] cacheNames = CacheManager.getInstance().getCacheNames();  
  90.             System.out.println("缓存的key cacheNames length := "  
  91.                     + cacheNames.length);  
  92.             for (String name : cacheNames) {  
  93.                 System.out.println("name := " + name);  
  94.             }  
  95.   
  96.             System.out.println("====================================");  
  97.             System.out.println("同一个session(一级缓存默认的)中,配置cache的Bean");  
  98.   
  99.             System.out.println("session open ....");  
  100.             try {  
  101.                 Session session = sessionFactory.getCurrentSession();  
  102.                 String hsql = "select t from EhBlogTopic t ";  
  103.                 ta = session.beginTransaction();  
  104.                 Query query = session.createQuery(hsql);  
  105.                 query.setCacheable(true);  
  106.                 System.out.println("查询全部query.list().size:"  
  107.                         + query.list().size());  
  108.   
  109.                 Cache myCache1 = CacheManager.getInstance().getCache(  
  110.                         "michael.cache.ehcache.hibernate.EhBlogTopic");  
  111.                 System.out.println("查询到EhBlogTopic cache size:"  
  112.                         + myCache1.getKeys().size());  
  113.                 myCache1 = CacheManager.getInstance().getCache(  
  114.                         "michael.cache.ehcache.hibernate.EhBlogTopic");  
  115.                 System.out.println("EhBlogTopic cache size:"  
  116.                         + myCache1.getKeys().size() + ",详细记录如下:");  
  117.                 for (Object str : myCache1.getKeys()) {  
  118.                     System.out.println(str);  
  119.                 }  
  120.   
  121.                 System.out  
  122.                         .println("在同一个session,再根据ID=1查询记录时不会再去查数据库,故不会打印hsql");  
  123.                 EhBlogTopic vo1 = (EhBlogTopic) session.get(EhBlogTopic.class,  
  124.                         1);  
  125.                 System.out.println("根据ID=1找到的记录:" + vo1);  
  126.                 EhBlogTopic vo2 = new EhBlogTopic();  
  127.                 vo2.setId(10);  
  128.                 vo2.setUserId("michael");  
  129.                 vo2.setTopic("Myblog:11");  
  130.                 vo2.setSite("http://sjsky.iteye.com");  
  131.                 session.save(vo2);  
  132.                 ta.commit();  
  133.                 System.out.println("新增加一条记录ID=10");  
  134.             } catch (Exception e) {  
  135.                 e.printStackTrace();  
  136.                 ta.rollback();  
  137.             }  
  138.             System.out.println("session closed.");  
  139.   
  140.             System.out.println("====================================");  
  141.             Cache myCache1 = CacheManager.getInstance().getCache(  
  142.                     "michael.cache.ehcache.hibernate.EhBlogTopic");  
  143.             System.out.println("EhBlogTopic cache size:"  
  144.                     + myCache1.getKeys().size() + ",详细记录如下:");  
  145.             for (Object str : myCache1.getKeys()) {  
  146.                 System.out.println(str);  
  147.             }  
  148.   
  149.             System.out.println("====================================");  
  150.             System.out.println("在当前同一个sessionFactory,配置cache的bean");  
  151.             System.out.println("session open ....");  
  152.             try {  
  153.                 Session session = sessionFactory.getCurrentSession();  
  154.                 ta = session.beginTransaction();  
  155.                 System.out  
  156.                         .println("不管是否第一次查询ID=1的记录,如果cache中存在的,则不会再查数据库,故不打印hsql");  
  157.                 EhBlogTopic vo1 = (EhBlogTopic) session.get(EhBlogTopic.class,  
  158.                         1);  
  159.                 System.out.println("根据ID=1找到的记录:" + vo1);  
  160.                 System.out.println("查询之前session保存的数据ID=10,也不会再查数据库,故不打印hsql");  
  161.                 EhBlogTopic vo2 = (EhBlogTopic) session.get(EhBlogTopic.class,  
  162.                         10);  
  163.                 System.out.println("根据之前save的ID=10找到的记录:" + vo2);  
  164.                 ta.commit();  
  165.             } catch (Exception e) {  
  166.                 e.printStackTrace();  
  167.                 ta.rollback();  
  168.             }  
  169.             System.out.println("session closed.");  
  170.         } catch (Exception e) {  
  171.             e.printStackTrace();  
  172.         } finally {  
  173.             if (null != sessionFactory) {  
  174.                 sessionFactory.close();  
  175.   
  176.             }  
  177.         }  
  178.         System.out.println("sessionFactory  closed.");  
  179.     }  
  180. }  

 

 运行结果如下:

 

ehcache - hibernate Test ...
2011-12-15 13:27:15 net.sf.ehcache.hibernate.AbstractEhcacheProvider buildCache
警告: Could not find a specific ehcache configuration for cache named [michael.cache.ehcache.hibernate.EhBlogTopic]; using defaults.
2011-12-15 13:27:15 net.sf.ehcache.hibernate.AbstractEhcacheProvider buildCache
警告: Could not find a specific ehcache configuration for cache named [michael.cache.ehcache.hibernate.EhBlogTopic2]; using defaults.
2011-12-15 13:27:15 net.sf.ehcache.hibernate.AbstractEhcacheProvider buildCache
警告: Could not find a specific ehcache configuration for cache named [michael.cache.ehcache.hibernate.EhBlogTopic3]; using defaults.
buildSessionFactory===============
====================================
session open ....
同一个session(一级缓存默认的)中,没有配置cache的Bean
Hibernate: select ehuserinfo0_.ID as ID1_, ehuserinfo0_.USER_ID as USER2_1_, ehuserinfo0_.USER_NAME as USER3_1_, ehuserinfo0_.OHTER_INFO as OHTER4_1_ from MY_TB_EH_USER_INFO ehuserinfo0_
查询全部query.list().size:2
再根据ID=1查询某记录时不会再去查数据库,故不会打印hsql
根据ID=1找到的记录:michael.cache.ehcache.hibernate.EhUserInfo@63b2e6
session closed.
session open ....
第一次根据ID=1查询某记录时,会打印hsql
Hibernate: select ehuserinfo0_.ID as ID1_0_, ehuserinfo0_.USER_ID as USER2_1_0_, ehuserinfo0_.USER_NAME as USER3_1_0_, ehuserinfo0_.OHTER_INFO as OHTER4_1_0_ from MY_TB_EH_USER_INFO ehuserinfo0_ where ehuserinfo0_.ID=?
根据ID=1找到的记录:michael.cache.ehcache.hibernate.EhUserInfo@123a389
session closed.
====================================
当前同一个sessionFactory,没有配置cache的Bean,
session open ....
第一次根据ID=1查询记录时会再去查数据库,故打印hsql如下:
Hibernate: select ehuserinfo0_.ID as ID1_0_, ehuserinfo0_.USER_ID as USER2_1_0_, ehuserinfo0_.USER_NAME as USER3_1_0_, ehuserinfo0_.OHTER_INFO as OHTER4_1_0_ from MY_TB_EH_USER_INFO ehuserinfo0_ where ehuserinfo0_.ID=?
根据ID=1找到的记录:michael.cache.ehcache.hibernate.EhUserInfo@429c19
session closed.
====================================
缓存的key cacheNames length := 7
name := sampleCache2
name := michael.cache.ehcache.hibernate.EhBlogTopic2
name := org.hibernate.cache.UpdateTimestampsCache
name := sampleCache1
name := michael.cache.ehcache.hibernate.EhBlogTopic
name := org.hibernate.cache.StandardQueryCache
name := michael.cache.ehcache.hibernate.EhBlogTopic3
====================================
同一个session(一级缓存默认的)中,配置cache的Bean
session open ....
Hibernate: select ehblogtopi0_.ID as ID2_, ehblogtopi0_.USER_ID as USER2_2_, ehblogtopi0_.TOPIC as TOPIC2_, ehblogtopi0_.SITE as SITE2_ from MY_TB_EH_BLOG_TOPIC ehblogtopi0_
查询全部query.list().size:9
查询到EhBlogTopic cache size:9
EhBlogTopic cache size:9,详细记录如下:
michael.cache.ehcache.hibernate.EhBlogTopic#6
michael.cache.ehcache.hibernate.EhBlogTopic#5
michael.cache.ehcache.hibernate.EhBlogTopic#7
michael.cache.ehcache.hibernate.EhBlogTopic#8
michael.cache.ehcache.hibernate.EhBlogTopic#2
michael.cache.ehcache.hibernate.EhBlogTopic#9
michael.cache.ehcache.hibernate.EhBlogTopic#1
michael.cache.ehcache.hibernate.EhBlogTopic#4
michael.cache.ehcache.hibernate.EhBlogTopic#3
在同一个session,再根据ID=1查询记录时不会再去查数据库,故不会打印hsql
根据ID=1找到的记录:michael.cache.ehcache.hibernate.EhBlogTopic@11a0d35
Hibernate: insert into MY_TB_EH_BLOG_TOPIC (USER_ID, TOPIC, SITE, ID) values (?, ?, ?, ?)
新增加一条记录ID=10
session closed.
====================================
EhBlogTopic cache size:10,详细记录如下:
michael.cache.ehcache.hibernate.EhBlogTopic#6
michael.cache.ehcache.hibernate.EhBlogTopic#5
michael.cache.ehcache.hibernate.EhBlogTopic#7
michael.cache.ehcache.hibernate.EhBlogTopic#8
michael.cache.ehcache.hibernate.EhBlogTopic#2
michael.cache.ehcache.hibernate.EhBlogTopic#9
michael.cache.ehcache.hibernate.EhBlogTopic#10
michael.cache.ehcache.hibernate.EhBlogTopic#1
michael.cache.ehcache.hibernate.EhBlogTopic#4
michael.cache.ehcache.hibernate.EhBlogTopic#3
====================================
在当前同一个sessionFactory,配置cache的bean
session open ....
不管是否第一次查询ID=1的记录,如果cache中存在的,则不会再查数据库,故不打印hsql
根据ID=1找到的记录:michael.cache.ehcache.hibernate.EhBlogTopic@1321f5
查询之前session保存的数据ID=10,也不会再查数据库,故不打印hsql
根据之前save的ID=10找到的记录:michael.cache.ehcache.hibernate.EhBlogTopic@1a6518
session closed.
sessionFactory closed.

 

   我们从上面的详细运行日志中就可以看出cache的效果。

 

 

本文连接:http://sjsky.iteye.com/blog/1312132