执行原生INSERT查询触发org.postgresql.util.PSQLException的问题求助
问题:原生INSERT查询执行成功但抛出"No results were returned by the query"错误
问题重现
实体类代码
@Entity @Table(name = "users") @Getter @Setter public class Users{ @Id @SequenceGenerator(name = "cons_seq", sequenceName = "cons_seq", allocationSize = 100) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cons_seq") @Column(name = "id", nullable = false) private Long id; @Column(name = "created_by") private String created_by; }
Repository代码
@Repository public interface ProfileRepository extends JpaRepository<Users, Long> { @Query(value = """ INSERT INTO users (id, created_by) VALUES (nextval('cons_seq'), :createdBy) """, nativeQuery = true) void create(@Param("createdBy") String createdBy); } // 服务层调用代码 public void create(final Profile profile) { profileRepository.create("test"); // 原代码语法错误已修正 }
错误信息
Caused by: org.postgresql.util.PSQLException: No results were returned by the query.
注:数据库中记录已成功插入,但仍抛出上述错误。
解决方案
核心修改点
- 添加
@Modifying注解:在Repository的create方法上标注@Modifying,告知Spring Data JPA这是一个DML修改操作,不需要返回结果集。 - 添加事务注解:确保调用该Repository方法的上层服务方法带有
@Transactional,因为DML操作必须在事务上下文内执行。
修改后的代码示例
修改后的Repository
@Repository public interface ProfileRepository extends JpaRepository<Users, Long> { @Modifying @Query(value = """ INSERT INTO users (id, created_by) VALUES (nextval('cons_seq'), :createdBy) """, nativeQuery = true) void create(@Param("createdBy") String createdBy); }
修改后的服务层代码
@Transactional public void create(final Profile profile) { profileRepository.create("test"); }
原因说明
@Modifying是Spring Data JPA专门用于标识INSERT/UPDATE/DELETE这类无返回结果的修改型查询的注解,不加的话,框架会默认期望查询返回结果集,从而触发"No results were returned"的异常。- 所有DML操作都需要事务支持,因此必须在调用该方法的上层方法(如服务层方法)添加
@Transactional注解,否则会抛出TransactionRequiredException。
更优替代方案(推荐)
如果没有特殊业务需求,建议直接使用JpaRepository自带的save方法,实体类已配置序列生成器,JPA会自动处理ID的生成,代码更简洁且符合JPA规范:
@Transactional public void create(final Profile profile) { Users user = new Users(); user.setCreated_by("test"); profileRepository.save(user); }
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

