2

I have a question regarding the caching in spring boot application. I have simple web application where I manage one entity, use Spring Data JPA, JCache with Hazelcast implementation. I've created two caches:

  • One caches entity by id
  • Another one by entity field value and list of entities as cache value

When I remove single value from the system I just evict this value from first cache and evict the whole list of entities from the second one if there is the record with respective key (field value). My question: is there any solution don't to remove the whole record from second cache but update it, just remove one entity from the cache value list?

Example:

import com.google.gwt.thirdparty.guava.common.collect.Lists;
import com.test.mmm.jcache.entity.Person;
import com.test.mmm.jcache.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PersonService {

    private final PersonRepository personRepository;

    @Caching(put = @CachePut(value = "persons", key = "#person.id"),
            evict = @CacheEvict(value = "personsByLastName", key = "#person.lastName"))
    public Person save(Person person) {
        return personRepository.save(person);
    }

    @Caching(evict = {
            @CacheEvict(value = "persons", key = "#person.id"),
            @CacheEvict(value = "personsByLastName", key = "#person.lastName")
    })
    public void delete(Person person) {
        personRepository.delete(person.getId());
    }

    @Cacheable(value = "persons", key = "#id")
    public Person findOne(Long id) {
        return personRepository.findOne(id);
    }

    @Cacheable(value = "personsByLastName", key = "#lastName")
    public List<Person> findByLastName(String lastName) {
        return personRepository.findByLastName(lastName);
    }

    public List<Person> findAll() {
        return Lists.newArrayList(personRepository.findAll());
    }

    @Autowired
    public PersonService(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }
}
Marian
  • 387
  • 3
  • 17

0 Answers0