1
votes

I am working on a second-level Hazelcast cache. The cache is working perfectly fine with the findAll method but when I am trying to update existing data or adding new data and again trying to gather all data using the findAll method it gives old records not updated one. Here I Attached my code. The highlight is when I'm trying to fetch data using the findById method it gives me updated data from the cache itself. I don't want to use @CacheEvit.

@Override
@CachePut(cacheNames = "cache",key="#profileDTO.id")
public ProfileDTO save(ProfileDTO profileDTO) {
    log.debug("Request to save Profile : {}", profileDTO);
    
    Profile profile = profileMapper.toEntity(profileDTO);
    profile = profileRepository.save(profile);
    return profileMapper.toDto(profile);
}

/**
 * Get all the profiles.
 *
 * @return the list of entities.
 */
@Override
@Cacheable(cacheNames = "cache")
public List<ProfileDTO> findAll() {
    log.debug("Request to get all Profiles");
    return profileRepository.findAll().stream()
        .map(profileMapper::toDto)
        .collect(Collectors.toCollection(LinkedList::new));
}
/**
 * Get one profile by id.
 *
 * @param id the id of the entity.
 * @return the entity.
 */
@Override
@Transactional(readOnly = true)
@Cacheable(cacheNames = { "cache" },key = "#id")
public Optional<ProfileDTO> findOne(Long id) {
    log.debug("Request to get Profile : {}", id);
    return profileRepository.findById(id)
        .map(profileMapper::toDto);
}
1

1 Answers

0
votes

You don't provide the complete sources, but I'm afraid you conflate two different things.

One one-side, there's Spring Cache. You configure it with the @Cacheable annotation. Spring Cache adds only individual elements, not collections (cf. the relevant GitHub issue closed with declined).

On the other side, there's Hibernate second-level cache that can be configured via Spring Boot's application.properties (or YAML). Here's a sample project that has it properly configured. It allows to cache entities in collections returned by repositories.

The two caches are orthogonal.

I'd suggest you remove Spring Cache from the equation and use Hibernate's second-level cache only.