How to call SQL dateAdd method using JPA @Query

99封情书 提交于 2019-12-13 02:46:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!