spring - 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);
}
解决方案
如果结果为 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){
}
}
推荐阅读
- python - 使用python像素到图像
- python - 如何编写将数据作为 csv 文件接收并返回标准化 pandas DataFrame 的函数?
- swift - 按下按钮时将形状动态放置在屏幕上的某个位置 - SwiftUI
- c - 如何使用 strcmp() 将输入与多个字符串(字符串数组)进行比较?
- react-native - 滚动 FlatList 时出现空白
- awk - 这是间接使用 IEEE754 double 将 unsigned big int 转换为所需的位/字节的可行方法吗
- android - 如何优化 viewModel 工厂代码?
- linux - SVN | 突然添加新文件问题 | 运行上下文错误:服务器意外关闭了连接
- swift - 我在哪里可以声明我的 NSMenu 触发器?
- javascript - 将数组传递给 blazors IJSRuntime.InvokeAsync