title: How to cache results of a Spring Data JPA query method without using query cache?
body: <p>I have a Spring Boot app with Spring Data JPA (hibernate backend) repository classes. I've added a couple custom finder methods, some with specific <code>@Query</code> annotation to tell it how to get the data. I have already set up EhCache for the hibernate 2nd level cache, but so far, the only way I can get these results caching is to enable the hibernate query cache. I'd prefer to define a specific cache and store the actual domain objects there just as if it were a normal finder. Below is my repo code: </p>
  
  <pre><code>public interface PromotionServiceXrefRepository extends PagingAndSortingRepository&lt;PromotionServiceXref, Integer&gt; {
  
    @Query("SELECT psx FROM Customer c " +
           "JOIN c.customerProductPromotions cpp " +
           "JOIN cpp.productPromotion pp " +
           "JOIN pp.promotion p JOIN p.promotionServiceXrefs psx " +
           "WHERE c.customerId = ?1")
    @QueryHints(@QueryHint(name = "org.hibernate.cacheable", value = "true"))
    @Cache(usage = CacheConcurrencyStrategy.READ_ONLY, region = "promotionServiceXrefByCustomerId")
    Set&lt;PromotionServiceXref&gt; findByCustomerId(int customerId);
  }
  </code></pre>
  
  <p>And here is the "promotionServiceXrefByCustomerId" cache I defined, that is NOT being used: </p>
  
  <pre><code>&lt;cache name="promotionServiceXrefByCustomerId" overflowToDisk="true" diskPersistent="true"
         maxEntriesLocalHeap="3000000" eternal="true" diskSpoolBufferSizeMB="20" memoryStoreEvictionPolicy="LFU"
         transactionalMode="off" statistics="true"&gt;
  &lt;/cache&gt;
  </code></pre>
  
  <p>What am I doing wrong? If I enable <code>StandardQueryCache</code> then this data gets cached there and hibernate does not execute a query. But when I disable the query caching, this does not get cached. What am I doing wrong here? PLEASE HELP!</p>