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.