JPQL SELECT 不检索更新的数据

问题描述

我有一个控制器方法来执行这两个操作:

  1. 更新客户名称

  2. 数据库中检索更新的客户

customerRepository.updateCustomerName(customerId,name);
Customer updatedCustomer = customerRepository.searchCustomer(customerId);

这些是各自的存储库方法

@Modifying
@Query("UPDATE Customer c SET c.name = ?2 WHERE c.customerId = ?1")
public int updateCustomerName(Long customerId,String name);

@Query("SELECT c FROM Customer c WHERE c.customerId =?1")
public Customer searchCustomer(Long customerId);

更新工作正常。

执行时,名称数据库中正确更新。

我面临的问题是 searchCustomer 方法返回带有旧数据(更新前的名称)的 Customer 对象。

不知道为什么。

这段代码不应该再次查询数据库并检索更新的数据吗?

解决方法

试试 @Modifying(clearAutomatically = true) 在接下来的查询中清除缓存并强制对数据库进行新的选择

也许您应该在查询之前使用 flushAutomatically = true 来刷新实体