How can I update cache with CachePut?

Viewed 1030

My @Cacheable method has next signature:

@Component
public class UpcomingFilter implements Filter<Entity> {

    @Cacheable(value = {"upcoming"})
    @Override
    public List<Entity> filter(int limit) {
       //retrieve from repository
    }
}

This filter use the reporisoty, take limit as parameter for pagination and return List of Entities. I'm trying to update cache when add Entity to the system:

@CachePut(value={"upcoming", "popular", "recentlyAdded", "recommendations", "thisWeek", "topRated"})
    public Entity addEntity(RequestDto dto, User user) {
        //do work, create and save entity to repository
        return entity;
    }

But after adding new entity to the system it is not updated. Filters returns old values. I saw examples, where for CachePut and Cacheable the word 'key' is used, but how can I add

@Cacheable(key="#entity.id") 

to the Filter signature ?

UPDATE

Tried to add my key:

@CachePut(value={"upcoming","popular", "recentlyAdded", "recommendations", "thisWeek", "topRated"},
            key = "#root.target.FILTER_KEY", condition = "#result != null")
    public Entity addEntity(RequestDto dto, User user) {
            //do work, create and save entity to repository
            return entity;
        }

and also add key to @Cacheable:

public static final String FILTER_KEY = "filterKey";
@Cacheable(value = {"recentlyAdded"}, key = "#root.target.FILTER_KEY")
    @Override
    public List<Entity> filter(int limit) {

and than I get

java.lang.ClassCastException: com.java.domain.Entity cannot be cast to java.util.List

1 Answers

Instead @CachePut the @CacheEvict should be used. It works for me:

 @CacheEvict(value={"upcoming", "popular", "recentlyAdded", "recommendations", "thisWeek", "topRated"},
            allEntries = true, condition = "#result != null")
        public Entity addEntity(RequestDto dto, User user) {
            //do work, create and save entity to repository
            return entity;
        }
Related