在Spring / Hibernate中正确使用缓存 [英] Proper cache usage in Spring / Hibernate

查看:107
本文介绍了在Spring / Hibernate中正确使用缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Project X包含以下几部分:

a。 Spring数据存储库具有不同的方法,如:

  @Cacheable(value =xobjects,unless =#result == null )
XObject findByParamA(String paramA);

@Cacheable(value =xobjects,除非=#result == null)
XObject findByParamB(String paramB);

@CacheEvict(xobjects)
< E扩展XObject> E保存(E实体);



b。 Hibernate也使用xobjects缓存。

问题1
由于有2种方法可以将对象添加到缓存中,是同一个对象出现2次的情况。如何更好地解决这个问题?例如使用结果对象中的键。例如:


key =#result.id

问题2
当调用save方法时,我不想从缓存中逐出所有对象,但我不确定当前的实现是否可行。 保存方法有xobject作为输入,所以CacheEvict将它用作驱逐的关键,没有我期望会发生的事情。在这里,我相信能够像上面一样使用魔术键的方法是很好的。



更新#1 其实我认为我的提案可以工作,下面是一个示例 - https://github.com/zhangkaitao/spring4-showcase/blob/master/spring-cache/src/main/java/com/sishuok/spring/service/UserService2.java
但我需要先测试它。稍后将分享结果。

解决方案

您的方法要么不起作用,要么很难维护。除了需要手动维护缓存之外,如果希望管理它们,则需要将实体实例重新合并到每个新的Hibernate会话(持久性上下文)中,因为从您自己的缓存中返回的实体将始终被分离。 / p>

最好的方法是使用Hibernate的二级缓存,它会自动为您执行缓存条目生命周期作业。


Project X has the following parts:

a. Spring Data repository with separate methods like:

@Cacheable(value = "xobjects", unless = "#result == null")
XObject findByParamA(String paramA);

@Cacheable(value = "xobjects", unless = "#result == null")
XObject findByParamB(String paramB);

@CacheEvict("xobjects")
<E extends XObject> E save(E entity);

b. Hibernate that also uses "xobjects" cache.

Problem #1 Since there are 2 ways of adding object to cache it could be the situation when the same object appears 2 times. How to solve this better? For example using key from result object. Something like:

key = "#result.id"

Problem #2 I do not want to evict all objects from cache when "save" method is called but I am not sure that current implementation will work. "save" method has xobject as input so CacheEvict will use it as a key for eviction and nothing that I expect will happen. Here I believe it would be nice to be able to use the same approach with magic key as above.

UPDATE #1 Actually I think my proposal can work, here is a sample - https://github.com/zhangkaitao/spring4-showcase/blob/master/spring-cache/src/main/java/com/sishuok/spring/service/UserService2.java But I need to test it first. Will share the results later.

解决方案

Your approach will either not work or will be very difficult to maintain. Besides the need for maintaining the cache manually, you would need to merge the entity instances back into each new Hibernate session (persistence context) if you want them to be managed, because the entities you return from your own cache will always be detached.

The best approach is to use Hibernate second-level cache which will do cache entries lifecycle job for you automatically.

这篇关于在Spring / Hibernate中正确使用缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆