【问题标题】:PSQLException trying to inject string in query Spring Boot JPAPSQLException 试图在查询 Spring Boot JPA 中注入字符串
【发布时间】: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 &gt;= ?1") List&lt;Issue&gt; findByMaxCreatedAt(LocaleDateTime createdAt);
  • 我认为你应该像 SELECT * FROM issue WHERE created_at &gt;= timestamp '?1' 一样引用它。或者最好不要使用String 作为参数类型并使用TimestampLocalDateTime。所以查询将是SELECT * FROM issue WHERE created_at &gt;= ?1
  • @YCF_L postgresql 只会将结果复制到一个单元格中
  • @Alex 我会尽快尝试

标签: java postgresql spring-boot hibernate


【解决方案1】:

如果你真的必须使用字符串,你将不得不强制转换参数:

@Query(value = "SELECT * FROM issue WHERE created_at >= cast(?1 as timestamp)", nativeQuery = true)

【讨论】:

  • 我会尽快尝试
猜你喜欢
  • 2021-01-13
  • 2021-10-13
  • 2017-03-08
  • 1970-01-01
  • 2017-04-22
  • 2021-09-15
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多