Spring Data JPA - 该语句未返回结果集

时间:2016-09-16 14:17:25

标签: spring spring-data spring-data-jpa

在我的应用程序中,我有一个与父/子关系中的自身相关的模型。帖子可以有父母也是帖子。我已经编写了一个查询来删除目标帖子及其后代。当我在Spring之外执行查询时,它完美地工作。但是,在Spring中运行它时,查询会成功执行,但会引发以下异常:

WARN  SqlExceptionHelper:144 - SQL Error: 0, SQLState: null
ERROR SqlExceptionHelper:146 - The statement did not return a result set.
ERROR [dispatcherServlet]:182 - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.

我的查询从扩展JpaRepository

的接口运行
@Query(value = "WITH ParentTree AS (\n" +
            "  SELECT Parent.post_key,\n" +
            "    1 AS Level\n" +
            "  FROM community_post AS Parent\n" +
            "    WHERE Parent.post_key = ?1\n" +
            "    UNION ALL\n" +
            "      SELECT Child.post_key,\n" +
            "        pt.Level + 1\n" +
            "      FROM community_post AS Child\n" +
            "      INNER JOIN ParentTree AS pt\n" +
            "        ON Child.post_parent = pt.post_key\n" +
            "      WHERE Child.post_parent IS NOT NULL\n" +
            ")\n" +
            "DELETE FROM community_post\n" +
            "  WHERE post_key IN (\n" +
            "      SELECT post_key\n" +
            "      FROM ParentTree\n" +
            "  )", nativeQuery = true)
    void recursiveDelete(long targetKey);

2 个答案:

答案 0 :(得分:5)

我想你也想添加@Modifying注释。请参阅文档here。这是因为SQL Delete不返回结果集。

编辑1:

如果您熟悉JDBC API,则归结为执行(或executeQuery)与executeUpdate。看起来Spring期望使用@Query注释的方法将返回结果集,因此当它没有时它会失望。相关的SO问题/答案here

答案 1 :(得分:0)

如果 @Query 缺少 @Modification 注释。