问题
I have to search for row, which is older than 6 months. I have insert time(datetime) as one of the column in my table. if it would have been a sql query, it is straight forward like this :-
select * from myTable where insertTime<=dateadd(month, -6, getDate());
But I am using JPA, so I had to write something like this :-
select * from myTable where insertTime<=function('DATEADD',month, -6, function('getDate'));
I am not sure how to put month paramater in above query.
I am getting following error on above query
Error creating bean with name 'myRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query ....
How should I put month field in above query? Is it possible through JPA?
Thanks in advance.
回答1:
Thanks to SPeL support you can try to use the following trick:
public interface MyEntityRepo extends JpaRepository<MyEntity, Integer> {
@Query("select e from MyEntity e where e.createdAt <= ?#{@myEntityRepo.sixMonthsBefore()}")
List<MyEntity> getAllSixMonthsOld();
default Instant sixMonthsBefore() {
return Instant.now().minus(6, ChronoUnit.MONTHS);
}
}
来源:https://stackoverflow.com/questions/50821879/how-to-call-sql-dateadd-method-using-jpa-query