Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check date between two other dates spring data jpa

I have this model:

public class Event {     private String name;     private Date start;     private Date end; } 

and repository as

@Repository public interface EventRepository extends JpaRepository<Event, Long> {     List<Event> findByEventTypeAccount(Account account); } 

What I want to do is, I will pass one date and need to check that date is between start and end e.g. (I will pass Sept 30 as date and need to find all entries which have Sept 30 between their start and end)

Something like findDateisBetweenStartAndEnd(Date date)?

like image 218
Don Jose Avatar asked Sep 30 '16 05:09

Don Jose


People also ask

How do I extract data between two dates in spring boot?

We can get the dates between two dates with single method call using the dedicated datesUntil method of a LocalDate class. The datesUntill returns the sequentially ordered Stream of dates starting from the date object whose method is called to the date given as method argument.

What does findById return in JPA?

Its findById method retrieves an entity by its id. The return value is Optional<T> . Optional<T> is a container object which may or may not contain a non-null value. If a value is present, isPresent returns true and get returns the value.

What is @query used for spring data?

Spring Data JPA @Query The @Query annotation declares finder queries directly on repository methods. While similar @NamedQuery is used on domain classes, Spring Data JPA @Query annotation is used on Repository interface. This frees the domain classes from persistence specific information, which is a good thing.

Is JPA between inclusive?

The BETWEEN operator can be used in conditional expressions to determine whether the result of an expression falls within an inclusive range of values. Numeric, string, and date expressions can be evaluated in this way.


2 Answers

You should take a look the reference documentation. It's well explained.

In your case, I think you cannot use between because you need to pass two parameters

Between - findByStartDateBetween … where x.startDate between ?1 and ?2

In your case take a look to use a combination of LessThan or LessThanEqual with GreaterThan or GreaterThanEqual

  • LessThan/LessThanEqual

LessThan - findByEndLessThan … where x.start< ?1

LessThanEqual findByEndLessThanEqual … where x.start <= ?1

  • GreaterThan/GreaterThanEqual

GreaterThan - findByStartGreaterThan … where x.end> ?1

GreaterThanEqual - findByStartGreaterThanEqual … where x.end>= ?1

You can use the operator And and Or to combine both.

like image 89
Pau Avatar answered Sep 21 '22 15:09

Pau


I did use following solution to this:

findAllByStartDateLessThanEqualAndEndDateGreaterThanEqual(OffsetDateTime endDate, OffsetDateTime startDate); 
like image 28
Michaël Cuypers Avatar answered Sep 17 '22 15:09

Michaël Cuypers