【发布时间】:2021-05-26 11:34:14
【问题描述】:
我想查找特定列(即时间戳)大于特定时间戳的所有记录...所有这些都使用 PostgreSQL。
我有以下存储库:
public interface IssuePublicationRepository extends IssueRepository {
@Query(value = "SELECT * FROM issue WHERE created_at >= timestamp ?1", nativeQuery = true)
List<Issue> findByMaxCreatedAt(String createdAt);
}
我是这样使用它的:
issueRepository.findByMaxCreatedAt(
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ITALY)
.format(new Date(Instant.now().toEpochMilli() - 10L*30*24*60*60*1000)
)
); // just a random date
但是我得到了:
2021-05-26 13:23:39.431 DEBUG 96462 --- [nio-8080-exec-1] org.hibernate.SQL : SELECT * FROM issue WHERE created_at >= timestamp ?
Hibernate: SELECT * FROM issue WHERE created_at >= timestamp ?
2021-05-26 13:23:39.432 TRACE 96462 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [2020-07-30 13:23:39]
2021-05-26 13:23:39.438 WARN 96462 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42601
2021-05-26 13:23:39.438 ERROR 96462 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: syntax error at or near "$1"
Posizione: 51
2021-05-26 13:23:39.457 ERROR 96462 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
但是,如果我运行
SELECT * FROM issue WHERE created_at >= timestamp '2020-07-30 13:21:41'
在我的 DBMS 上,它运行良好
【问题讨论】:
-
尝试使用
@Query(value = "SELECT i FROM issue i WHERE i.createdAt >= ?1") List<Issue> findByMaxCreatedAt(LocaleDateTime createdAt); -
我认为你应该像
SELECT * FROM issue WHERE created_at >= timestamp '?1'一样引用它。或者最好不要使用String作为参数类型并使用Timestamp或LocalDateTime。所以查询将是SELECT * FROM issue WHERE created_at >= ?1 -
@YCF_L postgresql 只会将结果复制到一个单元格中
-
@Alex 我会尽快尝试
标签: java postgresql spring-boot hibernate