Reputation: 29
I'm working on a Spring Boot application where I have a scenario to put @CachePut
and @CacheEvict
on the same method.
I tried the scenario with this code given below :
@CachePut(value="myValue",key="#entity.getId(),#entity.getOrgId()",
cacheManager="no-expire-caching")
@CacheEvict(value="myValue", key="#entity.getId(),#entity.getOrgId()",
cacheManager="no-expire-caching", condition="#entity.isDeleted() == true")
public MyEntity save(boolean flag, MyEntity entity){
if (flag==true){
entity.setIsDeleted(true);
return myRepo.save(entity);
}
return myRepo.save(entity);
}
But this doesn't seem to work as expected.
Objectives :
I want @CachePut
annotation to always execute first since that will be the first validation to update the cache.
@CacheEvict
is executed whenever the condition is satisfied (i.e. isDeleted
field is set to true
)
I don't want my cache to be updated or add a new entry if isDeleted
is set to true
.
Is it possible to achieve this in Spring ? How should I modify my code ?
Upvotes: 1
Views: 5299
Reputation: 16439
You can achieve the use of multiple different cache annotations on the same method in Spring using @Caching
annotation.
Note: This works when different caches are used.
According to Spring Cache Abstraction Docs:
When multiple annotations such as
@CacheEvict
or@CachePut
is needed to be specified on the same method for different caches.
Then to achieve this, the workaround is to use
@Caching
.@Caching
allows multiple nested@Cacheable
,@CachePut
and@CacheEvict
to be used on the same method.
Try this (if it works) :
@Caching(put={@CachePut(value="myValue",key="#entity.getId(),#entity.getOrgId()",
cacheManager="no-expire-caching")}, evict = {@CacheEvict(value="myValue", key="#entity.getId(),#entity.getOrgId()",
cacheManager="no-expire-caching", condition="#entity.isDeleted() == true")})
public MyEntity save(boolean flag, MyEntity entity){
if (flag==true){
entity.setIsDeleted(true);
return myRepo.save(entity);
}
return myRepo.save(entity);
}
@Caching Java Docs for reference.
Upvotes: 1