日期:2014-05-17  浏览次数:20697 次

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="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.provider_configuration_file_resource_path">
/ehcache-hibernate-local.xml
</property>
Submenu.hbm.xml
<hibernate-mapping>
  <class name="HibernateDAO.Submenu" table="submenu" schema="dbo" catalog="erp">
<cache usage="read-only"/>
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>

<ehcache>

<diskStore path="d:\\cache"/>
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
<cache name="org.hibernate.cache.StandardQueryCache"  
  maxElementsInMemory="50" eternal="false" timeToIdleSeconds="1800"  
  timeToLiveSeconds="3600" overflowToDisk="true" />  
  <cache name="org.hibernate.cache.UpdateTimestampsCache"  
  maxElementsInMemory="5000" eternal="true" overflowToDisk="true" />  
  <cache name="myCacheRegion" maxElementsInMemory="10" eternal="false"  
  timeToIdleSeconds="3600" timeToLiveSeconds="7200" overflowToDisk="true" />  
<cache name="HibnateDAO.Submenu" maxElementsInMemory="500"
overflowToDisk="true" eternal="true">

</cache>
</ehcache> 
test.java
package Test;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;

import HibernateDAO.HibDao;
import HibernateDAO.Submenu;

public class Test {
public static void main(String[] args) {
HibDao hd=new HibDao();
Session session=hd.creatsession();
Query q=session.createQuery("from Submenu");
List<Submenu> list=q.list(); 
q.setCacheable(true);
for (int i = 0; i < list.size(); i++) {
Submenu s=list.get(i);
System.out.println(s.getMenuname());
}
List<Submenu> list2=q.list();
for (int i = 0; i < list2.size(); i++) {
Submenu s=(Submenu) list2.get(i);
System.out.println(s.getMenuname());
}
session.close();
}

}
Console:
Hibernate: select submenu0_.id as id2_, submenu0_.menuid as menuid2_, submenu0_.menuname as menuname2_, submenu0_.menulevel as menulevel2_, submenu0_.url as url2_ from erp.dbo.submenu submenu0_
用户操作
销售计划
Hibernate: select submenu0_.id as id2_, submenu0_.menuid as menuid2_, submenu0_.menuname as menuname2_, submenu0_.menulevel as menulevel2_, submenu0_.url as url2_ from erp.dbo.submenu submenu0_
用户操作
销售计划
求解惑:明显是查询了2次数据库。 而换成load()就是可以的!

------解决方案--------------------
list方法,不会使用缓存

get/load/iterator的遍历 可以使用缓存