简体   繁体   English

使用Spring Data JPA和Postgresql将字符串转换为@Query中的时间戳

[英]String convert to timestamp in @Query using Spring Data JPA and postgresql

I would like to get from Postgresql all records before chosen date. 我想从Postgresql获取选定日期之前的所有记录。 Date is String. 日期是字符串。 In my opinion the easiest way is to convert string into timestamp using to_timestamp. 在我看来,最简单的方法是使用to_timestamp将字符串转换为时间戳。

select * from workers where update_date < to_timestamp('2018-08-11', 'YYYY-MM-DD')::timestamp without time zone;

I created method in my repository like bellow but it doesn't work. 我在像波纹管这样的存储库中创建了方法,但是它不起作用。

@Query("select w from Worker w where w.update_date < to_timestamp(:date, 'YYYY-MM-DD')::timestamp without time zone") 
List<Worker> findBeforeDate(@Param("date") String date);

It throws 它抛出

org.hibernate.hql.internal.ast.QuerySyntaxException : org.hibernate.hql.internal.ast.QuerySyntaxException
unexpected token: : near line 1, column 104 [ select w from com.oksa.workreport.doma.Worker w where w.update_date < to_timestamp(:date, 'YYYY-MM-DD')::timestamp without time zone] 意外令牌::靠近第1行第104列[ select w from com.oksa.workreport.doma.Worker w where w.update_date < to_timestamp(:date, 'YYYY-MM-DD')::timestamp without time zone]

Could anyone help me how to do this? 有人可以帮我怎么做吗?

You'll have to escape the colons in your query. 您必须在查询中转义冒号。 Try below: 请尝试以下方法:

@Query(value = "select w from Worker w where w.update_date < to_timestamp(:date, 'YYYY-MM-DD')\\:\\:timestamp without time zone", nativeQuery=true) 
List<Worker> findBeforeDate(@Param("date") String date);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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