hibernate ehcache 对象缓存

EHCache的使用场合

 

    1比较少更新表数据
        EhCache一般要使用在比较少执行write操作的表(包括update,insert,delete等)[Hibernate的二级缓存也都是这样];
    2 对并发要求不是很严格的情况
        两台机子中的缓存是不能实时同步的;

这是一个简单的  ehcache 对象缓存 例子

ehcache 对象缓存 的配置

    hibernate配置文件

 <session-factory>
 <property name="connection.username">root</property>
 <property name="connection.url">
  jdbc:mysql://localhost/test
 </property>
 <property name="dialect">
  org.hibernate.dialect.MySQLDialect
 </property>
 <property name="myeclipse.connection.profile">mysql</property>
 <property name="connection.password">root</property>
 <property name="connection.driver_class">
  com.mysql.jdbc.Driver
 </property>
 <property name="hbm2ddl.auto">update</property>
 <property name="show_sql">true</property>
 <!-- 设置Hibernate的缓存接口类,这个类在Hibernate包中  -->
 <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
 <!-- 是否启用查询缓存 -->
 <property name="cache.use_query_cache">true</property>
 <mapping resource="com/cache/entity/User.hbm.xml" />

</session-factory>

 

 

ehcache.xml 配置

 <defaultCache
     maxElementsInMemory="10000"
     eternal="false"
     overflowToDisk="true"
     timeToIdleSeconds="300"
     timeToLiveSeconds="180"
     diskPersistent="false"
     diskExpiryThreadIntervalSeconds= "120">
    </defaultCache>

在src 下放入 ehcache.xml、ehcache.xsd

java代码:

     /**     
 * @{#} 类名称: EhCache.java
 *    创建时间: Aug 31, 2009 2:31:05 PM     
 *         
 */      
package com.cache.test;      

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.cache.utils.HibernateSessionFactory;
     
/**     
 * @作者 <a href="http://qing393260529.iteye.com">黎青春</a>    
 * @版本 1.0     
 */

public class EhCache {

 public static void main(String[] args) {
  Session s = HibernateSessionFactory.getSession();
 
  Query query =s.createQuery("from User");
        query.setCacheable(true);  //这句必须要有
        System.out.println("第一次读取");
        List l = query.list();
        System.out.println(l.size());
        HibernateSessionFactory.closeSession();
       
      
        s = HibernateSessionFactory.getSession();
        query = s.createQuery("from User");
        query.setCacheable(true); //这句必须要有
        System.out.println("第二次读取");
        l = query.list();
        System.out.println(l.size());
        HibernateSessionFactory.closeSession();

 }
 
}
  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值