JPA - Returning entities that are After StartDate and Before EndDate

Suresh Atta picture Suresh Atta · Dec 20, 2017 · Viewed 19.7k times · Source

I have two dates in my entity. ie.

Date startDate;
Date endDate;

How do I query so that given a date, it will return all entities where the specified date lies between startDate and endDate?

I already tried the following:

findByStartDateAfterAndEndDateBefore(Date givenDate);

And Spring-Data-JPA didn't like this and running into errors. There is no specific error and the repo just can't be injected to my class.

What is the correct way? I know this can be done easily wqith Hibernate criteria or with Native SQL but trying to do that in Spring JPA.

Is this a problem with the query itself or some sort of incompatibility between the Date types Spring uses?

Tried findByStartDateAfterAndEndDateBefore(Date givenDate, Date givenDate) and that returns null however.

Answer

Sasha Shpota picture Sasha Shpota · Jan 9, 2018

You can't use only one parameter because of Spring Data restrictions, but you can workaround it using code like this:

List<AnEntity> findByStartDateBeforeAndEndDateAfter(Date startDate, Date endDate);

default List<AnEntity> findByStartDateBeforeAndEndDateAfter(Date givenDate) {
    return findByStartDateBeforeAndEndDateAfter(givenDate, givenDate);
}

This code should cover your needs. I also verified it with Spring Boot 1.5.9. using spring-data-get-started example.