Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA - The statement did not return a result set

In my application I have a model that relates to itself in a parent/child relationship. Posts can have parents that are also posts. I've written a query to delete a target post and its descendants. When I execute the query outside of Spring it works perfectly. However when running it in Spring, the query executes successfully but throws the following exception:

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.

My query runs from an interface that extends 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);
like image 296
Bobby Nichols Avatar asked Sep 16 '16 14:09

Bobby Nichols


1 Answers

I think you want to add the @Modifying annotation as well. See the documentation here. It's because SQL Delete does not return a resultset.

EDIT 1:

It comes down to execute (or executeQuery) vs executeUpdate if you're familiar with the JDBC API. Looks like Spring has the expectation that your method annotated with @Query will return a resultset and so it's disappointed when it doesn't. Related SO question/answer here.

like image 81
unigeek Avatar answered Nov 15 '22 04:11

unigeek