Hibernate3 二级缓存的使用配置细节

以下是使用hibernate二级缓存时常遇到的一些配置的详细解释,希望对各位有所帮助:

配置一:
hibernate.cfg.xml文件中增加
<!--开启二级缓存-->
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>  
<property name="hibernate.cache.use_query_cache">true</property>
配置二:
工程项目src文件下新建一个ehcache.xml文件,其内容为
<!--开启二级缓存-->
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<diskStore path="java.io.tmpdir" />
<defaultCache maxElementsInMemory="10000"  eternal="false" overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="180" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" />
</ehcache>
配置三:
为了缓存某类的对象,其hbm文件中需添加<cache usage="read-only"/>属性例如:
<?xml version="1.0"?>
<!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 - Hibernate Tools
-->
<hibernate-mapping>
    <class name="com.vogue.bbsphoto.entity.Forum"
    table="cdb_forums">
        <cache usage="read-only"/>
        <id name="ID" column="fid" unsaved-value="null">
            <generator class="increment" />
        </id>
        <property name="name" column="name" type="string" />
        <property name="type" column="type" type="string" />
    </class>
</hibernate-mapping>
配置四:
为了使用查询缓存,Query必须设置cacheable为true,query.setCacheable(true);
例如dao父类中用于hql查询的方法修改后为:
/**
     * 执行hql语句的查询
     * @param sql
     * @return
     */
    public List executeQuery(String hql){
        List list = new ArrayList();
        Session session = HibernateSessionFactory.currentSession();
        Transaction tx = null;
        Query query = session.createQuery(hql);
        query.setCacheable(true);
        try {
            tx = session.beginTransaction();
            list = query.list();
            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            HibernateSessionFactory.rollbackTransaction(tx);
           
        } finally {
            HibernateSessionFactory.closeSession();
        }
        return list;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值