首页 > 解决方案 > Spring Data JPA Repository 在 Save() 之后刷新缓存

问题描述

我们有一个学生实体,并实现了缓存。只有在数据库中找不到记录时,我们才执行插入记录。

它第一次运行良好,因为数据库中不存在记录。但是,如果我们第二次重新提交相同的请求,那么它会从缓存中获取学生实体并返回 null。(在 DB 中,它存在)因此尝试重新插入该数据并因唯一约束而失败。

有人可以帮忙,在这种情况下如何清除/更新缓存。

存储库代码片段:

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {

    @Cacheable(cacheNames="StudentCache", cacheManager="DepartmentCacheManager", sync=true)
    Student findByStudentId(String StudentId);
}

服务代码片段

Student student = studentRepository.findByStudentId(studentId);
if (student == null) {
    student= createStudentObject(studentId);
    studentRepository.save(student);
}

标签: springcachingspring-data-jpa

解决方案


如果结果为 null ,您可以使用它unless来指定不缓存结果,但它不适用于sync=true

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {

    @Cacheable(cacheNames="StudentCache", cacheManager="DepartmentCacheManager", unless="#result == null")
    Student findByStudentId(String StudentId);
}

如果一定要使用sync,可以考虑使用@CachePut保存学生后更新缓存。

public class StudentRepository{

    @CachePut(cacheNames="StudentCache", cacheManager="DepartmentCacheManager",key="#student.studentId")
    public Student save(Student student){

    }
}

推荐阅读