Kaarthik Raja
Kaarthik Raja

Reputation: 29

How to use @CachePut and @CacheEvict on the same method in a Spring Boot application?

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 :

Is it possible to achieve this in Spring ? How should I modify my code ?

Upvotes: 1

Views: 5299

Answers (1)

Anish B.
Anish B.

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

Related Questions