【发布时间】:2020-05-07 11:22:22
【问题描述】:
我正在学习 Spring Boot 缓存以将这个概念应用到我们组织的项目中,并且我制作了一个名为employee cache 的示例项目。我的控制器和服务组件中有四种方法 insert、update、get 和 getAll。对于 insert 和 get @Cacheable 工作正常。现在我第一次调用getAllEmployee() 然后它从数据库中获取数据。之后,我尝试使用@CachePut 进行更新,它会更新数据库中的值,然后我再次调用getAllEmployee(),然后它没有从缓存中返回更新的值。对于@CachePut,我还参考了documentation。我还参考了其他一些文档,例如this 和this,但我没有解决我的问题。另外,当我打电话时,不会引发错误。
我尝试的是
这是我来自EmplyeeController.java的两个API
@PostMapping(value = "/updateSalary")
private Boolean updateSalary(@RequestParam int salary, @RequestParam Integer id) {
return empService.updateSalary(salary, id);
}
@GetMapping(value = "/getAllEmployee")
private Object getAllEmployee() {
List<EmployeeMapping> empList = empService.getAllEmployee();
return !empList.isEmpty() ? empList : "Something went wrong";
}
这是我来自EmployeeService.java 的两种方法。我应用了不同的键来更新方法,但没有用。我的getAll() 方法没有参数,所以我尝试了here 的所有无参数方法的关键技术,然后我也没有得到任何结果。
@CachePut(key = "#root.method.name")
public Boolean updateSalary(int salary, int id) {
System.err.println("updateSalary method is calling in service");
if (empRepo.salary(salary, id) != 0) {
return true;
}
return false;
}
@Cacheable(key = "#root.method.name")
public List<EmployeeMapping> getAllEmployee() {
return empRepo.findAllEmployee();
}
这是我来自EmployeeRepository.java 的两种方法。我在EmployeeMetaModel.java 和EmployeeMapping.java 中使用了@SqlResultSetMappings 和@NamedNativeQueries,但是EmployeeMetaModel.java 中的本机查询没有错误,因为它是从数据库中给出结果的。
@Transactional
@Modifying
@Query("update employee_cache e set e.salary = ?1 where e.id = ?2")
int salary(int salary, int id);
@Query(name = "EmployeeListQuery", nativeQuery = true)
List<EmployeeMapping> findAllEmployee();
请帮助我摆脱这个问题,我只需要在调用 updateSalary() 之后使用 getAllEmployee() 从缓存中更新值。
【问题讨论】:
标签: java spring-boot spring-cache