我在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);
}
执行后,我得到下一个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)
因此,问题出在这里:
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();
}
如果我可以设置另一个QueryExecutor标志或使用Statement.RETURN_GENERATED_KEYS
调用update语句,则将解决该问题。但是现在看来,没有办法从Spring Data Repository中指定它。我知道我可以从存储过程中完成我想做的事情,但是它不像注释中的某些参数那么方便。
那么,您如何看待?应该将其视为Spring Data&Postgres JDBC中的错误吗?
UPD: 已开通Jira问题-https://jira.spring.io/browse/DATAJPA-1389