需要一个对最近 4 小时发布的帖子进行排序的 JPA 查询

Need a JPA query which sorts Posts, posted on last 4hours

@存储库 public 接口 PostRepository 扩展 JpaRepository {

Page<Post> findAllByCategory(Pageable pageable, Category category);


LocalDate dateBefore4Hours = LocalDate.now().minus(4, ChronoUnit.HOURS); //tried but couldnt figured it out


@Query("SELECT a FROM Post a WHERE a.createdDate  ") //none of sql keywords i've tried here didnt wor
Page<Post> findAllWithCreationDateTimeInLastFourHours();

}

如果您需要比较时间,您可以使用 LocalDateTime,因为 LocalDate 没有时间组件。因此,要获得 4 小时前的 LocalDateTime,您可以这样做:

LocalDateTime currentTimeMinus4Hours = LocalDateTime.now().minusHours(4L);

然后您可以在查询中使用它并对列进行排序,就像这样:

@Query("SELECT a FROM Post a WHERE a.createdDate > :currentTimeMinus4Hours ORDER BY a.createdDate")
Page<Post> findRecentPosts(LocalDateTime currentTimeMinus4Hours);