我在我的 Web 应用程序中使用 hibernate ehcache。我缓存了如下所示的列表。
model.put("projecttype",sessionfactory.getCurrentSession().createCriteria(TblProjectType.class).list());
System.out.println("Fetch Count="+ stats.getEntityFetchCount());
System.out.println("Second Level Hit Count="+ stats.getSecondLevelCacheHitCount());
System.out.println("Second Level Miss Count="+ stats.getSecondLevelCacheMissCount());
System.out.println("Second Level Put Count="+ stats.getSecondLevelCachePutCount());
EHCACHE.xml
<cache
name="com.uniphore.timesheet.domain.TblProjectType"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true" statistics="true"/>
TblProjectType table has 5 rows only.
我的输出:
--First---
Fetch Count=0
Second Level Hit Count=0
Second Level Miss Count=0
Second Level Put Count=0
--Second---
Fetch Count=0
Second Level Hit Count=0
Second Level Miss Count=0
Second Level Put Count=11
---Third--
Fetch Count=0
Second Level Hit Count=0
Second Level Miss Count=0
Second Level Put Count=22
我的 Ebtity 类别:
@Entity
@Table(name="tblProjectType")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Repository
public class TblProjectType implements java.io.Serializable {
private static final long serialVersionUID = -1798070786993154681L;
@Id
@GeneratedValue
@Column(name ="ID")
private short id;
@Column(name ="TypeName")
private String typeName;
@Column(name="CreatedDate")
private Date createdDate;
@Column(name="ModifiedDate")
private Date modifiedDate;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "tblProjectType", cascade = CascadeType.ALL)
private Set<TblStage> tblStages = new HashSet<TblStage>(0);
@OneToMany(fetch = FetchType.LAZY, mappedBy = "tblProjectType", cascade = CascadeType.ALL)
private Set<TblProject> tblProjects = new HashSet<TblProject>(0);
//getters and setters
}
每次put计数增加11,但其他值没有改变。为什么二级缓存不命中?
为什么每次都执行查询而不是从二级缓存中取出结果?
为什么当我点击相同的查询时,第二级放置计数会增加,它应该更新而不是插入? 任何帮助将不胜感激!!!
最佳答案
尝试两件事。
在实体类中指定缓存区域
@Entity @Table(name="tblProjectType") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="yourcacheregion") @Repository public class TblProjectType implements java.io.Serializable { }
将条件查询标记为可缓存
model.put("projecttype",sessionfactory.getCurrentSession().createCriteria(TblProjectType.class)..setCacheable(true).list());
我假设您的 hibernate 配置如下
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider"/>
<property name="hibernate.generate_statistics" value="true"/>
关于java - 如何使用hibernate ehcache缓存列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27481214/