Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easier way to make a JPQL query with BETWEEN to include NULL values in properties

Tags:

java

jpa

jpql

I have a JPQL query

    @Query("SELECT e FROM Entry e WHERE :chosenDate BETWEEN e.periodFrom AND e.periodTo")
    List<Entry> findByChosenDate(LocalDate chosenDate);

There is a problem, that when one of the properties "periodFrom" or "periodTo" aren't set the entry won't be selected. I want that the query also include entires with one or two NULL values.

I want that the query select entries in three additional cases:

  1. When "periodFrom" is null and "periodTo" is null the entry should be found.

  2. When "periodFrom" is null and "periodTo" >=:chosenDate the entry should be found.

  3. When "periodFrom" <= :chosenDate and "periodTo" is null the entry should be found.

Is there an easier way to make such a query than :

    @Query("SELECT e FROM Entry e WHERE (:chosenDate BETWEEN e.periodFrom AND e.periodTo) 
        OR (e.periodFrom IS NULL AND e.periodTo IS NULL )
        OR ( e.periodFrom <= :chosenDate AND e.periodTo IS NULL)
        OR (e.periodFrom IS NULL AND e.periodTo >= :chosenDate)") 
    List<Entry> findByChosenDate(LocalDate chosenDate);
like image 883
PrzemyslawP Avatar asked Oct 23 '25 14:10

PrzemyslawP


1 Answers

I don't know if you find it better, but something like this would be shorter:

SELECT e FROM Entry e WHERE (:chosenDate BETWEEN COALESCE(e.periodFrom, 0000-01-01) AND COALESCE(e.periodTo, 9999-12-31) 
like image 89
TomekK Avatar answered Oct 25 '25 03:10

TomekK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!