You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring JPA查询报错query did not return a unique result:18 求助解决方案

解决Spring JPA "query did not return a unique result:18" 报错并实现指定客户订单查询

这个报错的核心原因很明确:你当前的Repository方法返回单个Order实例,但查询匹配到了18条订单记录,Spring JPA无法返回唯一结果,因此抛出异常。要实现你需要的查询(获取指定客户的所有订单且不关联customer表),只需要调整Repository方法的返回类型和定义方式即可,具体方案如下:

方案一:使用Spring Data JPA方法命名查询(推荐)

如果你的Order实体类中已经有对应数据库字段customer_id_fk的属性(比如命名为customerIdFk),直接在Repository中定义返回集合的方法:

public interface OrderRepository extends JpaRepository<Order, Long> {
    // 根据customer_id_fk查询所有订单,返回List集合
    List<Order> findByCustomerIdFk(Long customerId);
}

Spring Data JPA会自动根据方法名生成对应的SQL,就是你需要的select * from orders where customer_id_fk = ?,完全不会关联查询customer表,符合你的需求。

注意:如果实体类中对应的属性名是customerId(而非customerIdFk),方法名要改成findByCustomerId(Long customerId),保证和实体类属性名对应。

方案二:使用原生SQL自定义查询

如果你更倾向于写明确的SQL语句,确保只查询orders表即可,同时返回集合类型:

public interface OrderRepository extends JpaRepository<Order, Long> {
    @Query(value = "select * from orders where customer_id_fk = :customerId", nativeQuery = true)
    List<Order> findOrdersByCustomerId(@Param("customerId") Long customerId);
}

这里通过nativeQuery = true指定使用原生MySQL语句,SQL中仅操作orders表,不会关联customer表,返回List<Order>避免了唯一结果的异常。

调用示例

在业务代码中调用上述方法即可获取指定客户的所有订单:

List<Order> customerOrders = orderRepository.findByCustomerIdFk(1L);

内容的提问来源于stack exchange,提问作者sarah6

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 15:15:27