Check Date Between Two Other Dates Spring Data Jpa

Spring data date between query

You could use the following query:

Date date = //Input date
List<Product> = findByEffctDateAfterAndExpDateBefore(date, date);

Note that you have to enter date twice to match both 'where' clauses. This is under the assumption you are using Date objects, not literal Strings.

See JPA Repositories Table 2.3 for more info.

JPA query to filter before, after and between optional start and end dates

Here's a naïve solution using 4 methods and a switch. It's clunky, but it works. This approach can get particularly verbose if more complex JPQL or SQL queries need to be implemented, since the 4 Repository methods and queries would need to be duplicated.

Repository

@Repository
public interface MyRepository extends JpaRepository<MyObject> {
List<MyObject> findByDateBetween(Date beforeDate, Date afterDate);
List<MyObject> findByDateBefore(Date beforeDate);
List<MyObject> findByDateAfter(Date afterDate);
List<MyObject> findAll();

Service

public List<MyObject> search(Date startDate, Date endDate) {
int i = (startDate!=null ? 1 : 0) | (endDate!=null ? 2 : 0);
switch(i) {
case 0:
return repository.findAll();
case 1:
return repository.findByDateAfter(startDate);
case 2:
return repository.findByDateBefore(endDate);
case 3:
return repository.findByDateBetween(startDate, endDate);
}
}

(credit to this answer by Marc Gravell for the switch encoding)



Related Topics



Leave a reply



Submit