实现hibernate二级缓存,需要进行如下配置:
配置步骤一:
修改hibernate.cfg.xml文件,在配置中增加:
<!-- 开启查询缓存 -->
<property name="hibernate.cache.use_query_cache">true</property>
<!-- 开启二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 指定二级缓存提供商驱动 -->
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
配置步骤二:
在工程项目conf文件夹(依据项目修改路径,保证编译后在classes路径下即可)下新建一个ehcache.xml文件,其内容为:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<diskStore path="java.io.tmpdir" />
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
diskPersistent="false" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" />
</ehcache>
配置步骤三:
如果要缓存某对象,修改其hbm文件,在class节点下添加<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" >
<hibernate-mapping package="com.demo.entity">
<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;
}
完成上面的四个步骤,即可实现。但是在开发过程中可能会碰到问题:
1、报错:找不到net/sf/ehcache/CacheException类,问题是缺少ehcache.jar包
2、导入jar包后报错:
java.lang.IllegalAccessError: tried to access method net.sf.ehcache.CacheManager.<init>()V from class org.hibernate.cache.EhCacheProvider
因为版本不正确,可以从网上下载ehcache-1.2.3.jar 导入即可完成。问题解决
测试:在测试类中或者公共dao中增加
Statistics message=dao.sessionFactory.getStatistics();
System.out.println("二级缓存命中数:"+message.getSecondLevelCacheHitCount());
多次点击查询调用此方法,后台输出如果二级缓存命中数>0 则成功。
希望此文档对在此处碰到问题的人有所帮助。