0

I'm trying to call @CacheEvict and @Cacheable annotation on a single method.

@CacheEvict(value = "tripDetailsDashboardCache", key = "#userId")
@Cacheable(value ="tripDetailsDashboardCache", key="#userId")
public  List<DashBoardObject> getAllDetailsForDashBoard(Integer userId){
    List<Master> masters = tripDetailsService.getTripDetailsForCaching(userId);
    List<DashBoardObject> dashBoardObject = tripDetailsService.getMasterDetailsForDashBoard(userId, masters);
    return dashBoardObject;
}

On call of @CacheEvict, I want to delete the cached data for the particular key and again i want to cache the fresh data of the method response. But it is not caching the fresh data ?. And also it is not giving any error ?.

Shayan Ghosh
  • 882
  • 6
  • 14

3 Answers3

4

I think you want to update the cache, so try to use @CachePut, method will be executed in all cases, if the key is new, new record will be added in the cache, if the record is old, old value will be updated by new value (refresh the value).

@CachePut(value = "tripDetailsDashboardCache", key = "#userId")
public  List<DashBoardObject> getAllDetailsForDashBoard(Integer userId){
    List<Master> masters = tripDetailsService.getTripDetailsForCaching(userId);
    List<DashBoardObject> dashBoardObject = tripDetailsService.getMasterDetailsForDashBoard(userId, masters);
    return dashBoardObject;
}
Safwan Hijazi
  • 2,089
  • 2
  • 17
  • 29
0

@CacheEvict runs by default after the method invocation. So the method above does the caching the list with key #userId and then clear the cache completely .

it makes the code unclear I’d recommend creating separate cacheable and cache-evict methods

Shayan Ghosh
  • 882
  • 6
  • 14
  • I created separate cacheable and cache-evict methods. but it is not working as i required. requirement is i will book a ticket, it will be stored in a DB, after that i will call these two cache methods, Next i will click dashboard button, in that time it should take data from cache, but it is not taking. and No Error. – user2852071-Santhosh Apr 26 '16 at 10:44
  • I want to call both CacheEvict and Cacheable on a same method. because first i want delete the data from the cache and then i want load the fresh data. Is it possible to call both annotation on same method. – user2852071-Santhosh Apr 26 '16 at 10:55
  • "beforeInvocation = true" setting can be used. but it's hard to predict who win: CacheEvict or Cacheable – Yura May 11 '17 at 11:07
0

Look at docs. There are @Caching annotation where you can define your @Cacheable, @CachePut and @CacheEvict

Yura
  • 1,733
  • 1
  • 20
  • 19