hibernate 二级

另一个文章:http://www.ineeke.cn/archives/HibernateCacheLevelTwo/

配置一:
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;
}

实验结果:


补充一下:当要缓存的对象处于级联关系中时。如果和他存在级联关系的对象都有属性 <cache usage="read-only"/>那么,在第一次get后该对象所处的对象图中的所有对象都会保存到hibernate的二级缓存中,在第二次get该对象时,直接从二级缓存中找到所有级联的对象;如果其中某个级联对象没有<cache usage="read-only"/>属性,则不会被保存到二级缓存中,以后每次get时仍然会执行sql去数据库中找该级联对象。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值