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

Viewed 36

@Repository public interface PostRepository extends 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();

}

1 Answers

If you need to compare time you may use LocalDateTime, because LocalDate don't have the time component. So to get the LocalDateTime of 4 hours ago you can do this:

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

Then you can just use that in your query and sort the column, just like so:

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