【问题标题】:Getting an "query did not return a unique result" error. How can I fix it?收到“查询未返回唯一结果”错误。我该如何解决?
【发布时间】:2022-07-28 00:48:41
【问题描述】:

我有一个包含各种表和内容的数据库,我使用了一个相当大的 SQL 查询,该查询从所有表中收集值并对其进行排序,以便我可以轻松地将结果导出为 CSV。

我通过 heidisql 创建了一个存储过程以通过 Java 触发查询。 为此,我决定使用表的存储库,该存储库仅存储最后一个单击按钮的用户的名称 + 该操作的时间戳,因为我想避免创建新实体。

当我手动执行查询时,我得到了 155 行的正确结果。但是当我点击按钮时,它会抛出一个错误:

Caused by: javax.persistence.NonUniqueResultException: query did not return a unique result: 155

155 没问题。我做错了什么?我需要改变什么才能让它发挥作用?

这里是它的一个小概述:

@Repository
public interface LogReportRepository extends JpaRepository<LogReport, Long>, Serializable {
    
        @Query(value = "CALL FORMAT_REPORT_DATA(:vonMonatParam,:bisMonatParam,:aggregationThresholdParam,:teamParam);", nativeQuery = true)
        ResultSet formatReportData(@Param("vonMonatParam") LocalDateTime fromMonth,
                                   @Param("bisMonatParam") LocalDateTime untilMonth,
                                   @Param("aggregationThresholdParam") int aggregationThreshold,
                                   @Param("teamParam") int team);
    }
@Service
public class LogReportImpl implements LogReportService {

    @Autowired
    LogReportRepository logReportRepository;


    @Override
    public ResultSet formatReportData(LocalDateTime fromMonth, LocalDateTime untilMonth, int aggregationThreshold, int team) {
        return logReportRepository.formatReportData(fromMonth,untilMonth,aggregationThreshold,team);
    }
}
public interface LogReportService {
    
    ResultSet formatReportData(LocalDateTime fromMonth, LocalDateTime untilMonth, int aggregationThreshold, int team);
}

我用 wicket 制作了一个测试网站,并将其放在按钮后面。 这是按钮的类:

public class FormatButton extends Button {

    @SpringBean
    public LogReportService logReportService;

    public FormatButton(String id, IModel<String> model) {
        super(id, model);
    }

    @Override
    public void onSubmit() {
        LocalDateTime fromMonth = LocalDateTime.of(2022,6,30,23,59,0);
        LocalDateTime untilMonth = LocalDateTime.of(2022,8,1,0,0,0);
        int aggregationThreshold = 37;
        int team = 1;

        ResultSet resultSet = logReportService.formatReportData(fromMonth,untilMonth,aggregationThreshold,team);
    }
}

【问题讨论】:

    标签: java mysql spring-boot hibernate jpa


    【解决方案1】:

    错误告诉你 Spring Data 期望的是单个结果,而不是 155。

    我认为问题在于formatReportData 的签名没有返回集合。如果ResultSet 是一个实体或一个DTO,它应该是:

    @Query(...)
    List<ResultSet> formatReportData(...);
    

    或者,您可以使用更通用的:

    @Query(...)
    List<Object[]> formatReportData(...);
    

    【讨论】:

      猜你喜欢
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 2015-10-30
      • 1970-01-01
      • 2020-01-22
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多