gpt4 book ai didi

hibernate - 非唯一结果异常 : JPARepository Spring boot

转载 作者:行者123 更新时间:2023-12-02 01:00:17 25 4
gpt4 key购买 nike

我将 SpringBootJPAQueryDSL 一起使用。我已经编写了一个 HQL 来从表中获取一些自定义记录,但它抛出了 Exception。下面我提到存储库的代码:

@Repository
public interface LoanOfferRepository extends JpaRepository<LoanOffer, Long>, QuerydslPredicateExecutor<LoanOffer> {

@Query("select lo.startDate,count(*) from LoanOffer lo where lo.loan.fsp= :fsp and lo.startDate between :fromDate and :toDate Group by lo.startDate")
public Map<LocalDate,Integer> getLastMonthLoans(@Param("fsp")Fsp fsp,@Param("fromDate")LocalDate fromDate,@Param("toDate")LocalDate toDate);
}

每当我调用此方法时 getLastMonthLoans() 我都会遇到以下异常:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.IncorrectResultSizeDataAccessException: query did not return a unique result: 9; nested exception is javax.persistence.NonUniqueResultException: query did not return a unique result: 9] with root cause

javax.persistence.NonUniqueResultException: query did not return a unique result: 9

代码或查询或返回类型有什么问题吗?查询似乎工作正常。

最佳答案

您的查询结果无法映射到Map<LocalDate,Integer> .

您可以尝试返回 List<Object[]>而不是 Map .

@Query("select lo.startDate,count(*) from LoanOffer lo where lo.loan.fsp= :fsp and lo.startDate between :fromDate and :toDate Group by lo.startDate")
public List<Object[]> getLastMonthLoans(@Param("fsp")Fsp fsp,@Param("fromDate")LocalDate fromDate,@Param("toDate")LocalDate toDate);

然后解析List<Object[]>Map你需要。

这样:

Map<LocalDate, Integer> mappedResult = new HashMap<>();
List<Object[]> queryResult = loanOfferRepository.getLastMonthLoans(fsp, fromDate, toDate);
for (Object[] obj : queryResult ) {
LocalDate ld = (LocalDate) obj[0];
Integer count = (Integer) obj[1];
mappedResult.put(ld, count);
}

关于hibernate - 非唯一结果异常 : JPARepository Spring boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51150748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com