kan*_*e77 3 java caching hibernate
我有多对一的关系,假设用户有公司.公司实体没有任何其他关系.
如果我为公司的findAll hibernate查询启用二级缓存,第二次重新加载页面(这意味着加载了用户,然后还加载了所有公司的列表)我为每个现有公司选择(从公司选择...)其中id =?)在hibernate输出中.调用findAll for Company时会发生这种情况,它看起来像这样(这是类中的泛型方法,使用适当的类型进行扩展):
return (List<T>) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Criteria c = session.createCriteria(persistentClass);
c.setCacheable(cacheFindAll);
return c.list();
}
});
Run Code Online (Sandbox Code Playgroud)
我在只读策略中使用Jboss TreeCacheProvider.如果我使用setCacheable(false)没有"不需要的"选择.
为什么会发生这种情况?如何消除这种行为?
调用setCacheable()用于启用查询缓存,请参阅javadoc:
Enable caching of this query result, provided query caching is enabled for the underlying session
会发生什么是公司的ID被缓存但不是对象本身.如果启用二级缓存,则这些单独的公司查询将由二级缓存处理.
为了启用二级缓存,您需要在persistence.xml中设置hibernate.cache.use_second_level_cache = true.此外,您需要注释您想要在二级缓存中缓存的关系和实体.
@OneToMany
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
private List<Company> companies;
Run Code Online (Sandbox Code Playgroud)
和实体缓存:
@Entity
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class Company {
...
}
Run Code Online (Sandbox Code Playgroud)
BTW二级缓存只会缓存你在id上找到的关系和实体.查询不能由二级缓存缓存,并且将始终转到数据库(或查询缓存).
| 归档时间: |
|
| 查看次数: |
3818 次 |
| 最近记录: |