使用JPA时如何解决Postgres中的“查询未返回结果”异常

kri*_*hna 2 java postgresql jpa spring-data-jpa

嗨,我正在构建一个REST服务,以使用JPA从PostgreSQL删除实体。代码是:

@Repository
public interface TestRepo  extends JpaRepository<Question, Long>{
    @Query(value = "delete from testmodel c where c.id in ?1 and c.name=?2",
            nativeQuery = true)
    void deleteModel(List<Long> ids, String text);
}
Run Code Online (Sandbox Code Playgroud)

代码工作正常,条目已从PostgreSQL中删除,但我在终端中收到以下异常。

org.postgresql.util.PSQLException: No results were returned by the query.
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:107) ~[postgresql-42.2.5.jar:42.2.5]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.2.0.jar:na]
Run Code Online (Sandbox Code Playgroud)

当我搜索此异常时,我建议使用executeUpdate而不是executeQuery。

由于我使用的是JPA,所以我不知道如何用executeUpdate替换executeQuery

任何帮助将是巨大的。

Elg*_*yed 5

您需要添加@Modifying以声明这是一个更新查询,并且您不希望数据库返回结果

@Repository
public interface TestRepo  extends JpaRepository<Question, Long>{
    @Modifying
    @Query(value = "delete from testmodel c where c.id in ?1 and c.name=?2",
            nativeQuery = true)
    void deleteModel(List<Long> ids, String text);
}
Run Code Online (Sandbox Code Playgroud)