Spring Boot JPA-@Modification(clearAutomatically=true)没有刷新缓存



我正在使用Spring Boot数据JPA来更新表中的一列。我的数据库是Postgres。我正在尝试更新数据库中statusCode列的值。我正在将其从1更新为6。以下是相同的代码:

存储库

public interface MailRecordRepository extends JpaRepository<MailRecords, Integer> {
// Fetch the rows which are new in status
List<MailRecords> findTop100ByEmailStatusCode(int statusCode);
// Update status to in-progress
@Modifying(flushAutomatically = true, clearAutomatically = true) //, flushAutomatically = true
@Query(value = "UPDATE users.usertbl SET statusCode = :inProgressStatusCode where " +
"statusCode = 1 RETURNING *;", nativeQuery = true)
public List<MailRecords> updateRecordsToInProgress(
@Param("inProgressStatusCode") int inProgressStatusCode);
}

我正试图通过在Postgres支持的原生查询中使用RETURNING关键字来获取更新的行。我将查询返回的更新行分配给一个列表,并在控制台中打印它。但是更新后的列表返回statusCode列的旧值,即1,而不是更新后的值,即6以下是相同的代码:

服务类别

public class MailServiceImpl implements MailService {
@Autowired
private MailRecordRepository mailRecordRepository;
@Autowired
private MailHandler mailHandler;
@Autowired
private EntityManager entityManager;
@Override
public List<MailRecords> getMailRecords() {
return (List<MailRecords>) mailRecordRepository.findAll();
}
@Override
public List<MailRecords> processEmailRecords() {
//fetch records from DB which are in new status
List<MailRecords> mailRecordsToBeSent = mailRecordRepository.findTop100ByEmailStatusCode(1);
// update the status to in-progress
//entityManager.clear();
List<MailRecords> updatedMailRecords = mailRecordRepository.updateRecordsToInProgress(6);
return updatedMailRecords;
}

如果我使用实体管理器的clear方法,更新后的值就会得到反映。但我试图理解为什么属性@Modifying(flushAutomatically = true, clearAutomatically = true)没有清除缓存值?为什么我必须显式调用entityManager.clear()?有人能纠正我的理解吗;我哪里错了?

我有点惊讶,返回的实体确实有效。

但我有一个可能发生的理论,你可以用调试器来验证:

  1. 语句执行,更新数据库中的行
  2. 该语句返回具有更新值的ResultSet
  3. JPA实现(Hibernate?(忽略除id之外的所有内容,并使用它们在一级缓存中查找实体并返回这些实体
  4. Spring Data JPA执行刷新并清除一级缓存。然后返回在步骤3中从JPA实现中得到的任何内容

您已经找到了解决方法。

最新更新