【问题标题】:How to rewrite postgresSql query as Spring-data jpa query如何将 postgresql 查询编写为 Spring-data jpa 查询
【发布时间】:2020-06-09 14:03:00
【问题描述】:

我在尝试将下一个查询编写为 spring-data JPA 查询时被卡住了:

with recursive s as (
select *
from t
where file_id = '12345'
union all
select dfs.*
from t dfs
join s on s.file_id = dfs.parent_folder_id
)
select * from s;

我已经尝试了下一个:

@Query(value = "with recursive subfiles as (
select * from t where file_id=?1 
union all 
dfs.* from t dfs join subfiles s 
on s.file_id = dfs.parent_folder_id) 
select file_id from subfiles", nativeQuery = true)

但我得到下一个错误:

Method threw 'org.springframework.dao.InvalidDataAccessResourceUsageException' exception.
could not extract ResultSet; SQL [n/a]
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.postgresql.util.PSQLException: ERROR: syntax error at or near "dfs"

查询应列出特定 id 的所有直接或间接依赖子项。 (类似的帖子here

【问题讨论】:

  • 当您直接在 postgresql 客户端中执行查询时,它是否在 @Query 注释中运行?注释在什么样的方法上?它有没有像Pageable 这样的附加参数?
  • 是的,它运行正常,但我设法修复了它。
  • 它出现了一个错误,因为我为 t 表使用了静态最终变量。不幸的是,值字段只接受编译时常量。

标签: java sql postgresql hibernate spring-data-jpa


【解决方案1】:

我已经设法使用下一种格式修复它:

@Query(nativeQuery = true,
value = "with recursive subfiles as " +
  "(select * " +
  "from t " +
  "where file_id=?1 " +
  "union all " +
  "select dfs.* " +
  "from t dfs " +
  "join subfiles s " +
  "on s.file_id = dfs.parent_folder_id) " +
"select file_id from subfiles")
List<String> listAllByParentId(String folderId);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 2021-05-01
    • 2017-04-25
    • 2015-05-11
    • 2017-05-13
    • 2022-01-23
    相关资源
    最近更新 更多