我有一个实体比赛如下:
class Tournament {
//other attributes
private LocalDate startDate;
private LocalDate endDate;
}
这表示从startDate到enddate运行几天/几个月的锦标赛。 我需要检索今天运行的所有锦标赛,此时此类似于 startDate< = today&& endDate> =今天,使用Spring JPA和分页。
我发现最接近的是:
@Repository
public interface TournamentRepository extends PagingAndSortingRepository<Tournament, Long> {
Page<Tournament> findByStartBeforeAndEndAfter(LocalDate date, LocalDate dateCopy, Pageable page); //today's date is passed as date and dateCopy
}
方法调用:
tournamentRepository.findByStartBeforeAndEndAfter(LocalDate.now(), LocalDate.now(), page);
这可以解释为 startDate&lt;今天&amp;&amp; endDate&gt;今天,所以如果锦标赛今天运行且仅持续1天,它就不起作用。
有没有更好的方法使用Spring JPA执行此操作而无需编写自定义查询?
答案 0 :(得分:1)
CURRENT_DATE
,CURRENT_TIME
,CURRENT_TIMESTAMP
是JPA中的预定义函数。你可以使用它。
试试这个
@Repository
public interface TournamentRepository extends PagingAndSortingRepository<Tournament, Long> {
@Query("Select t from Tournament t where t.startDate <= CURRENT_DATE and t.endDate >= CURRENT_DATE")
Page<Tournament> findByStartBeforeAndEndAfter(Pageable page);
}
答案 1 :(得分:1)
您可以使用@Query
注释并编写自己的查询,如下面的代码。
@Repository
public interface TournamentRepository extends PagingAndSortingRepository<Tournament, Long> {
@Query("select t from Tournament t where t.startDate <=:date and t.endDate >=: dateCopy")
Page<Tournament> findByStartBeforeAndEndAfter(@Param("date")LocalDate date,@Param("dateCopy") LocalDate dateCopy, Pageable page); //today's date is passed as date and dateCopy
}
您也可以尝试这样的native query
@Repository
public interface TournamentRepository extends PagingAndSortingRepository<Tournament, Long> {
@Query("select * from tournament where start_date <=:date and end_date >=: dateCopy",nativeQuery=true)
List<Tournament> findByStartBeforeAndEndAfter(@Param("date")LocalDate date,@Param("dateCopy") LocalDate dateCopy); //today's date is passed as date and dateCopy
}
答案 2 :(得分:0)
您可以使用LessThan,GreaterThan,LessThanEqual,GreaterThanEqual和日期。
@Repository
public interface TournamentRepository extends PagingAndSortingRepository<Tournament, Long> {
Page<Tournament> findByGreaterThanEqualStartDateAndLessThanEqualEndDate(LocalDate date, LocalDate dateCopy, Pageable page); //today's date is passed as date and dateCopy
}