关于hibernate:JPA Repository:设置符合条件的最新元素的字段 | 珊瑚贝

JPA Repository: set field of most recent element that matches criteria


我有一个 JpaRepository,它有许多匹配相同 myCriteria 的元素。我想更改匹配 myCriteria 的最新元素的布尔值。这是我的实体:

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);

}

似乎我没有正确使用 order by,因为我收到以下错误:expecting EOF, found ‘order’ near line 1。我的问题是如何正确构造这个查询?

感谢您的宝贵时间

  • 你使用什么hibernate方言?
  • spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect


首先我不得不说你不能在HQL/JPQL 中使用limit 子句。例如看这个问题。

第二个问题是您使用 UUID 类型作为实体的主键。
想象一下它是一个 Long 类型。在这种情况下,您将能够以这种方式重写您的查询:

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);

来源:https://www.codenong.com/63959453/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9636.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?