NonUniqueResultException:JPARepository Spring 启动

Jay*_*ary 3 hibernate hql spring-data-jpa spring-boot

我正在使用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);
}
Run Code Online (Sandbox Code Playgroud)

每当我调用此方法时,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
Run Code Online (Sandbox Code Playgroud)

代码、查询或返回类型有问题吗?不过,查询似乎工作正常。

hts*_*ame 5

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

您可以尝试使用 returnList<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);
Run Code Online (Sandbox Code Playgroud)

然后解析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);
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

18339 次

最近记录:

4 年,7 月 前