我有一个场景,需要先根据条件更新一些数据库记录,然后从数据库中读取这些记录。我正在使用 CrudReposirtory 并且在我的 Controller 中我有一个服务调用存储库方法使用 @Query 来更新记录并在下一行尝试读取相同的内容记录,但除非我不在该 Controller 方法中,否则记录不会更新。
请您参考如下方法:
如果执行 UPDATE 语句,则应将 @Modifying 与 @Query 结合使用。
来自文档:
@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2")
int setFixedFirstnameFor(String firstname, String lastname);
This will trigger the query annotated to the method as updating query instead of a selecting one. As the EntityManager might contain outdated entities after the execution of the modifying query, we automatically clear it (see JavaDoc of EntityManager.clear() for details). This will effectively drop all non-flushed changes still pending in the EntityManager. If you don't wish the EntityManager to be cleared automatically you can set @Modifying annotation's clearAutomatically attribute to false;

