Spring JPA method to find entities with beforeAndEqual a date AND afterAndEqual a date

Viewed 9602

I have an entity Tournament as follows:

class Tournament {
    //other attributes
    private LocalDate startDate;
    private LocalDate endDate;
}

This represents a tournament that runs for few days/months, from startDate to enddate. I need to retrieve all Tournaments that run today, at this moment, somthing like startDate <= today && endDate >= today, using Spring JPA and paging.

The closest I found was following:

@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

}

Method call:

tournamentRepository.findByStartBeforeAndEndAfter(LocalDate.now(), LocalDate.now(), page);

This can be interpreted as startDate < today && endDate > today, so it doesn't work if a tournament runs today and only for 1 day.

Is there a better way to do this using Spring JPA without having to write a custom query?

3 Answers
Related