首页 > 解决方案 > 使用 JPA 时如何解决 Postgres 中的“查询未返回任何结果”异常

问题描述

嗨,我正在构建一个休息服务,以使用 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);
}

代码工作正常,条目已从 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]

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

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

任何帮助都会非常有用。

标签: javapostgresqljpaspring-data-jpa

解决方案


您需要添加@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);
}

推荐阅读