无法使用INSERT从Spring Data Repository返回本机查询

rvi*_*t34 5 java postgresql spring-data-jpa

我在Spring Data JPA存储库中使用本机SQL查询,并且想在upsert后返回自动生成的ID。看起来像下面的类似片段:

public interface EntityRepository extends CrudRepository<Entity, Integer> {

    @Modifying
    @Transactional
    @Query(value = "INSERT INTO entity (name, age) VALUES(?1,?2) " +
                       "ON CONFLICT(name) DO UPDATE SET name=?1,age=?2 " +
                       "RETURNING id", nativeQuery = true)
    Integer upsert(String name, int age); 
}
Run Code Online (Sandbox Code Playgroud)

执行后,我得到下一个PSQLException:

Caused by: org.postgresql.util.PSQLException: A result was returned when none was expected.
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:141)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
Run Code Online (Sandbox Code Playgroud)

因此,问题出在这里:

org.postgresql.jdbc.PgPreparedStatement:

public int executeUpdate() throws SQLException {
   executeWithFlags(QueryExecutor.QUERY_NO_RESULTS);

   ResultWrapper iter = result;
   while (iter != null) {
     if (iter.getResultSet() != null) {
        throw new PSQLException(GT.tr("A result was returned when none was expected."),
        PSQLState.TOO_MANY_RESULTS);

     }
   iter = iter.getNext();
  }

return getUpdateCount();
}
Run Code Online (Sandbox Code Playgroud)

如果我可以设置另一个QueryExecutor标志或使用调用update语句,则将解决该问题Statement.RETURN_GENERATED_KEYS。但是现在看来,没有办法从Spring Data Repository中指定它。我知道我可以从存储过程中完成我想做的事情,但是它不像注释中的某些参数那么方便。

所以你怎么看?应该将其视为Spring Data&Postgres JDBC中的错误吗?

UPD:打开JIRA问题- https://jira.spring.io/browse/DATAJPA-1389