hibernate的二級緩存配置

 首先進行hibernate的二級緩存配置
第一步:.hibernate.cfg.xml 配置文件

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "
http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>
 <session-factory>
  <!-- JDBC驅動程序-->
  <property name="connection.driver_class">
   com.mysql.jdbc.Driver
  </property>
  <!-- 連接數據庫的URL-->
  <property name="connection.url">

   jdbc:mysql://localhost:3306/wy17113?characterEncoding=utf8
  </property>

  <!--連接的登錄名-->
  <property name="connection.username">root</property>

  <!--登錄密碼-->
  <property name="connection.password">root</property>

  <!-- C3P0連接池設定-->
  <property name="hibernate.connection.provider_class">
   org.hibernate.connection.C3P0ConnectionProvider
  </property>

  <property name="hibernate.c3p0.max_size">30</property>
  <property name="hibernate.c3p0.min_size">5</property>
  <property name="hibernate.c3p0.timeout">1800</property>
  <property name="hibernate.c3p0.max_statements">100</property>
  <property name="hibernate.c3p0.idle_test_period">120</property>
  <property name="hibernate.c3p0.acquire_increment">2</property>
  <property name="hibernate.c3p0.autoReconnect">true</property>

  <!--是否將運行期生成的SQL輸出到日誌以供調試-->
  <property name="show_sql">true</property>

  <!--指定連接的語言-->
  <property name="dialect">
   org.hibernate.dialect.MySQLDialect
  </property>
  
 
 <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
  <!-- 設置查詢緩存-->
  <property name="hibernate.cache.use_query_cache">true</property>
  <!-- 設置二級緩存-->
  <property name="hibernate.cache.use_second_level_cache">
   true
  </property>

  <mapping resource="com/wy17113/model/entity/Wy17113.hbm.xml"></mapping>
 </session-factory>
</hibernate-configuration>

第二步:定義*.hbm.xml 在xml開始部分定義二級緩存

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
     <class name="com.wy17113.model.entity.Jok" table="joks" >
      
  <cache usage="read-write"/>
        <id name="id" type="java.lang.String">
            <column name="id" precision="10" scale="0" />
            <generator class="uuid" />
        </id>
        <property name="title" type="java.lang.String">
            <column name="title" length="300" />
        </property>
        <property name="content" type="java.lang.String">
            <column name="content" length="2000" />
        </property>
               
        <property name="subDate" type="java.lang.String">
            <column name="subDate" length="22" />
        </property>
  <property name="type" type="java.lang.Integer">
            <column name="type"/>
        </property>
        <property name="ding" type="java.lang.Integer">
            <column name="ding"/>
        </property>
        <property name="cai" type="java.lang.Integer">
            <column name="cai"/>
        </property>  
       
        <set name="commentSet" inverse="false">
    <key column="jokId" on-delete="noaction" />
    <one-to-many class="com.wy17113.model.entity.Comment" not-found="exception" embed-xml="true" />
  </set>
    </class></hibernate-mapping>

第三步:定義ehcache.xml文件

<ehcache>

    <diskStore path="c:\\ehcache\"/>
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />

    <cache name="com.wy17113.model.entity.Jok"  緩存名字
        maxElementsInMemory="10000"   緩存裏可存放的最大對象數.
        eternal="false"  緩存對象是否永久有效(true表示是).  
        timeToIdleSeconds="300"      對象在緩存中存活的空閒時間,即空閒多久它就失效,單位是秒.  
        timeToLiveSeconds="600"   對象在緩存中存活的時間,單位是秒.  
        overflowToDisk="true"      當緩存溢出時,對象是否保存到磁盤上.保存的磁盤路徑由<diskStore>中的path指定.
        /> 
 
</ehcache>
dao裏面查詢代碼:

// 查詢所有
 @SuppressWarnings({ "deprecation", "unchecked" })
 public List<Jok> getAllJok(int type, String startTime, String endTime,
   int start, int count) throws SQLException {
  Session session = getSpringSession();
  Transaction ts = session.beginTransaction();
  List<Jok> jokList = null;
  try {
   Criteria criteria = session.createCriteria(Jok.class);
   
criteria.setCacheable(true);
   
   if (type != 0)
    criteria.add(Expression.eq("type", type));
   if (null != startTime && !startTime.equals(""))
    criteria.add(Expression.ge("subDate", java.sql.Date
      .valueOf(startTime)));
   if (null != endTime && !endTime.equals(""))
    criteria.add(Expression.le("subDate", java.sql.Date
      .valueOf(endTime)));
   criteria.addOrder(Property.forName("subDate").desc());

   criteria.setFirstResult(start);
   criteria.setMaxResults(count);
   
   jokList = criteria.list();
  } catch (HibernateException ex) {
   ts.rollback();
   ex.printStackTrace();
  }
  return jokList;
 }

到此就配置完成。

 

注意:

1,jar包版本問題、不能使用1.1版本、這樣會報異常信息、本文用的版本是ehcache-1.2.3.jar、在tomcat中、如果存在

兩個版本的jar包、他會默認加載低版本的、所以最好把相同的jar包低版本刪掉、

2,測試的時候 可以吧hql語句打印出來、在hibernate配置文件裏面吧 show_sql屬性設置成true就行。你會發現進行第一次查詢的時候會打印sql語句、第二次查詢的時候就不會打印sql語句、因爲走的是二級緩存。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章