Spring执行数据库更新报错:The statement did not return a result set
问题分析与解决
问题场景
数据库中手动执行UPDATE语句可正常更新数据,但通过Spring Data JPA调用时抛出错误,错误信息提示The statement did not return a result set。
相关代码
@Query(nativeQuery=true,value="update tbl_runningNumber set autoNum= autoNum+1 where cycle=:cycle and module=:module") String updateByCycle(@Param ("module")String module,@Param("cycle") int cycle);
报错日志
2023-02-01 16:17:47.651 WARN 21588 --- [nio-8082-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: null 2023-02-01 16:17:47.651 ERROR 21588 --- [nio-8082-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : The statement did not return a result set.
原因分析
UPDATE属于DML操作,执行后不会返回结果集,只会返回受影响的行数。但你定义的方法返回值为String,Spring Data JPA尝试将无结果的操作映射为String类型,导致抛出该错误。此外,Spring Data JPA默认认为@Query注解的方法是只读查询,执行更新操作时还需要添加@Modifying注解,否则会触发只读模式的异常。
解决方案
根据需求选择以下两种修改方式:
- 不需要获取受影响行数:将返回值改为
void,并添加@Modifying注解
@Modifying @Query(nativeQuery=true,value="update tbl_runningNumber set autoNum= autoNum+1 where cycle=:cycle and module=:module") void updateByCycle(@Param ("module")String module,@Param("cycle") int cycle);
- 需要获取受影响行数:将返回值改为
int(返回值代表被更新的行数),并添加@Modifying注解
@Modifying @Query(nativeQuery=true,value="update tbl_runningNumber set autoNum= autoNum+1 where cycle=:cycle and module=:module") int updateByCycle(@Param ("module")String module,@Param("cycle") int cycle);
内容的提问来源于stack exchange,提问作者Phortsophea MMO
相关产品推荐
相关产品推荐

