我在hibernate.cfg.xml,ehcache.xml中使用 Ehcache 配置了二级缓存。并在映射文件中设置了cache-usage属性。并检查数据是从缓存加载还是db使用hibenrate statices.But它没有加载。它再次执行查询。我提到了代码
<hibernate-configuration>
<session-factory>
<property name="connection.username">pension2</property>
<property name="connection.password">pension2</property>
<property name="connection.url">jdbc:oracle:thin:@191.161.0.25:1521:pension</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="myeclipse.connection.profile">pension</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.generate_statistics">true</property>
<property name="hibernate.cache.region.provider_class">
net.sf.ehcache.hibernate.EhCacheProvider</property>
<property name="hibernate.cache.provider_configuration_file_resource_path">/ehcache.xml </property>
<mapping resource="com/aims/mapping/Teacher.hbm.xml" />
<mapping resource="com/aims/mapping/Student.hbm.xml" />
<mapping resource="com/aims/mapping/Student_marks_detl.hbm.xml" />
<mapping resource="com/aims/mapping/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
ehcache.xml中
<ehcache> <diskStore path="java.io.tmpdir"/> <cache name="com.aims.beans.Teacher" maxElementsInMemory="300" eternal="false" overflowToDisk="false"/> </ehcache>
Mapping.xml
<hibernate-mapping>
<class name="com.aims.beans.Teacher" table="teacher">
<cache usage="read-write" />
<id name="tno" column="tno" type="java.lang.Integer" >
<generator class="assigned" />
</id>
<property name="tname" type="java.lang.String" column="tname"/>
</class>
</hibernate-mapping>
我尝试在jsp.So中加载教师列表,Iam使用createquery和setCacheable为真。
long oldHitCount = HibernateUtil.getHitCount();
long oldMissCount = HibernateUtil.getMissCount();
log.info(“oldHitCount”+ oldHitCount +“oldMissCount”+ oldMissCount); 查询q = session.createQuery(“来自老师”); q.setCacheable(真);
list = q.list(); long newHitCount = HibernateUtil.getHitCount();
long newMissCount = HibernateUtil.getMissCount();
HibernateUtil.getHitCount()/ HibernateUtil.getMissCount()代码
public static long getHitCount() {
long hitcount = 0;
hitcount = sessionFactory.getStatistics()
.getSecondLevelCacheStatistics("com.aims.beans.Teacher")
.getHitCount();
return hitcount;
}
public static long getMissCount() {
long miscount = 0;
miscount = sessionFactory.getStatistics()
.getSecondLevelCacheStatistics("com.aims.beans.Teacher")
.getMissCount();
return miscount;
}
但每次执行createQuery.I配置以及为什么它没有从缓存中返回。是否有任何错误配置二级缓存。请帮助我&gt;?
答案 0 :(得分:1)
二级缓存将id映射到实体,因此仅在通过id查询实体时使用。查询缓存将查询映射到查询检索的一组实体ID。因此,二级缓存和查询缓存实际上只在一起使用时才有用。
要启用查询缓存,仅设置查询可缓存是不够的,但您还必须在Hibernate session-factory
配置中启用查询缓存:
<property name="hibernate.cache.use_query_cache">true</property>
希望这有帮助。