【问题标题】:Cache is not updated using @CachePut不使用 @CachePut 更新缓存
【发布时间】:2025-12-14 18:40:01
【问题描述】:

我正在研究二级 Hazelcast 缓存。缓存使用 findAll 方法工作得非常好,但是当我尝试更新现有数据或添加新数据并再次尝试使用它提供的 findAll 方法收集所有数据时旧记录没有更新一个。在这里我附上了我的代码。重点是当我尝试使用 findById 方法获取数据时,它会为我提供来自缓存本身的更新数据。我不想使用@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);
}

【问题讨论】:

    标签: spring-boot caching hazelcast second-level-cache


    【解决方案1】:

    你没有提供完整的来源,但恐怕你把两个不同的东西混为一谈了。

    一方面,有 Spring Cache。您可以使用 @Cacheable 注释对其进行配置。 Spring Cache 仅添加单个元素,而不是集合(参见相关的 GitHub issue 关闭并拒绝)。

    另一方面,可以通过 Spring Boot 的application.properties(或 YAML)配置 Hibernate 二级缓存。这是一个正确配置的sample project。它允许在存储库返回的集合中缓存实体。

    这两个缓存是正交的。

    我建议你从等式中删除 Spring Cache,只使用 Hibernate 的二级缓存。

    【讨论】:

    • github.com/janu2024/… ----- 这里我附上了我的完整代码。
    • 您是否阅读了我的回答并做出了我建议的更改?
    • Hibernate 的二级缓存属性已经设置为 true 能否请您使用我的附加代码指导我
    • 我不明白为什么你的application.propertiesconfig 下而不是直接在src/main.resources 下。此外,您忘记提交 pom.xml 文件。
    • 我已经提交了其中所有丢失的文件,它是一个 jhipster 项目,因此 application.properties 文件作为其结构位于 config 文件夹中。