简体   繁体   中英

Spring JPA - JPQL Named Query Find All By Year And And month

I am trying to get all objects by specific month and year. I have done this with Native Query

   @Query(value = "select * from transaction_log as t where year(t.insurance_period)=(:year) AND user_id =(:userId) AND t.employer_id is null", nativeQuery = true)

And I want to be done with another way so I can use entity graphs etc. I have try

@Query("select t from Transaction t where year(t.insuranceDate) = ?1 and month(t.insuranceDate) = ?2")

And I get error on method Year () for unexcepted '('

and the following with the same error at EXTRACT method.

@Query("SELECT t FROM Transaction t WHERE EXTRACT (YEAR FROM t.insuranceDate) = :year AND EXTRACT (month FROMt.insuranceDate) = :month")

You could use BETWEEN first day of month and last day of month. According to jpql doc BETWEEN is inclusive.

The downside is doing some date calculations, but they are trivial with java.time classes. Let's say you want dates from February 2020. You could get first and last day like this:

int year = 2020;
int month = 2;
LocalDate firstDay = LocalDate.of(year, month, 1);
LocalDate lastDay = firstDay.withDayOfMonth(firstDay.lengthOfMonth());

Then the query will look like this:

@Query("SELECT t FROM Transaction t WHERE t.insuranceDate BETWEEN :firstDay AND :lastDay")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM