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)
?
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.
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.
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.
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.
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 - findByEndLessThan … where x.start< ?1
LessThanEqual findByEndLessThanEqual … where x.start <= ?1
GreaterThan - findByStartGreaterThan … where x.end> ?1
GreaterThanEqual - findByStartGreaterThanEqual … where x.end>= ?1
You can use the operator And
and Or
to combine both.
I did use following solution to this:
findAllByStartDateLessThanEqualAndEndDateGreaterThanEqual(OffsetDateTime endDate, OffsetDateTime startDate);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With