【问题标题】:Spring Data JPA Repository to refresh cache after Save()Spring Data JPA Repository 在 Save() 之后刷新缓存
【发布时间】:2019-05-28 09:58:41
【问题描述】:

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

第一次运行良好,因为数据库中不存在记录。但是,如果我们第二次重新提交相同的请求,那么它会从缓存中获取学生实体并返回 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);
}

【问题讨论】:

  • 我不清楚这句话“但是,如果我们第二次重新提交相同的请求,那么它会从缓存中获取学生实体并返回 null”为什么如果它已经在数据库中,它会返回 null 所以也在缓存中??
  • 在 find 方法中,我们已经明确告知要使用不同的缓存。 Hibernate 在保存期间使用它自己的缓存,而不是我提到的缓存。

标签: spring caching spring-data-jpa


【解决方案1】:

您可以使用unless指定如果结果为null则不缓存结果,但不适用于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){

    }
}

【讨论】:

  • 很高兴听到您解决问题。所以现在请考虑接受我的回答并给我的回答投票:D
  • 如果多个线程尝试更新同一个缓存变量会发生什么?会失败吗?
猜你喜欢
  • 2012-01-27
  • 1970-01-01
  • 2017-11-22
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
  • 2018-06-18
  • 2018-07-18
相关资源
最近更新 更多