JPA Repository: set field of most recent element that matches criteria
我有一个 JpaRepository,它有许多匹配相同
1 2 3 4 5 6 7 8 9 10 11 | @Entity @Table(name ="my_entity") @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class MyEntity { private boolean myField; private String myCriteria; private LocalDateTime createdAt; } |
这是我的存储库和查询:
1 2 3 4 5 6 7 | public interface MyRepository extends JpaRepository<MyEntity, UUID> { @Modifying @Query("update MyEntity myEntity set myEntity.myField = true where myEntity.myCriteria = :myCriteria order by myEntity.createdAt limit 1") void setAddressed(@Param("myCriteria") String myCriteria); } |
似乎我没有正确使用
感谢您的宝贵时间
首先我不得不说你不能在HQL/JPQL 中使用
第二个问题是您使用
想象一下它是一个
1 2 3 4 5 6 | public interface MyRepository extends JpaRepository<MyEntity, Long> { @Modifying @Query("update MyEntity m set m.myField = true where m.id = (select max(me.id) from MyEntity me where me.myCriteria = :myCriteria)") void setAddressed(@Param("myCriteria") String myCriteria); } |
但对于您的情况,我只看到一种方法 - 原生查询。
1 2 3 4 5 6 | public interface MyRepository extends JpaRepository<MyEntity, UUID> { @Modifying @Query(value ="update my_entity set my_field = true where my_id = (select my_id from my_entity where my_criteria = :myCriteria order by my_created_at limit 1)", nativeQuery = true) void setAddressed(@Param("myCriteria") String myCriteria); } |
为了补充接受的答案,这里是本机查询的诀窍:
1 2 3 4 5 6 | @Modifying @Query(value = "UPDATE my_entity SET my_field = true FROM" +"( SELECT * FROM my_entity WHERE my_criteria = :myCriteria ORDER BY created_at desc LIMIT 1 )" +"AS subquery WHERE my_entity.my_criteria = subquery.my_criteria", nativeQuery = true) void setAddressed(@Param("myCriteria") String myCriteria); |