title: Proper cache usage in Spring / Hibernate
body: <p>Project X has the following parts:</p>
  
  <p>a. Spring Data repository with separate methods like:</p>
  
  <pre><code>@Cacheable(value = "xobjects", unless = "#result == null")
  XObject findByParamA(String paramA);
  
  @Cacheable(value = "xobjects", unless = "#result == null")
  XObject findByParamB(String paramB);
  
  @CacheEvict("xobjects")
  &lt;E extends XObject&gt; E save(E entity);
  </code></pre>
  
  <p>b. Hibernate that also uses "xobjects" cache.</p>
  
  <p><strong>Problem #1</strong>
  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:</p>
  
  <blockquote>
    <p>key = "#result.id"</p>
  </blockquote>
  
  <p><strong>Problem #2</strong>
  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.</p>
  
  <p><strong>UPDATE #1</strong> Actually I think my proposal can work, here is a sample - <a href="https://github.com/zhangkaitao/spring4-showcase/blob/master/spring-cache/src/main/java/com/sishuok/spring/service/UserService2.java" rel="nofollow">https://github.com/zhangkaitao/spring4-showcase/blob/master/spring-cache/src/main/java/com/sishuok/spring/service/UserService2.java</a>
  But I need to test it first. Will share the results later.</p>