【发布时间】: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