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 String
s.
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
Arraylist - How to Check If an Index Exists
How to Set Environment Variable or System Property in Spring Tests
Prevent Multiple Login Using the Same User Name and Password
How to Find an Object in an Arraylist by Property
How to Sort Date in Descending Order Using Comparator
Setonclicklistener() on a Null Object Reference Error
Error: Incompatible Types: Int[][] Cannot Be Converted to Int
How to Check If a Json Key Exists
Convert Localdatetime to Localdatetime in Utc
Find Everything Between Two Xml Tags With Regex
Why Do I Get 404 for Rest With Spring-Boot
How to Process a Multipart Request Consisting of a File and a Json Object in Spring Restful Service
How to Identify File Type by Base64 Encoded String of a Image
Java Stream Collectors.Groupingby() Multiple Fields
Could Not Extract Resultset in Hibernate