2

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.

Alexey Anufriev
  • 366
  • 4
  • 16
  • 2
    Are you sure you want to use Spring Cache abstraction for this or use the 2nd level caching of your ORM provider as that does al those things automatically for you. – M. Deinum Jan 13 '16 at 10:31
  • I was thinking about this and it would be nice. I already marked XObject with @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) and enabled "hibernate.cache.use_second_level_cache". But the methods above are not cached. Will query cache helps? – Alexey Anufriev Jan 13 '16 at 11:11

1 Answers1

2

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.

Dragan Bozanovic
  • 21,631
  • 4
  • 36
  • 100