【发布时间】:2021-02-17 11:42:16
【问题描述】:
假设如下:
@Query("SELECT new so.dto.CustomerWithTotal(s, sum(sb.amount)) from Customer s LEFT join fetch Bills sb ON sb.customer.sq=s.sq and sb.periodFrom <= ?3 and sb.periodTo >= ?2 WHERE s.department.sq=?1 group by s")
List<CustomerWithTotal> findCustWithOrderTotal(Long departmentId, LocalDate from, LocalDate to);
和
public CustomerWithBillTotal(CustomerEo customer, BigDecimal amount) {
this.customer= customer;
this.amount = (amount != null) ? amount : BigDecimal.ZERO;
}
我正在尝试获取客户以及特定时期的订单总额。但是,当我检查执行的实际查询时,我会看到如下内容:
Hibernate: select customer.id as col_0_0_, sum(bill.amount) as col_1_0_ from customers...
Hibernate: select customer.id as cpx1_19_0_, customer.jpa_version as jpa_vers2_19_0_, ...
Hibernate: select customer.id as cpx1_19_0_, customer.jpa_version as jpa_vers2_19_0_, ...
Hibernate 仅在第一个查询中获取 id,然后单独请求每个客户,导致 N+1 个查询。如何让 Hibernate 在第一个查询中急切地获取 customer?最好不要在CustomerWithBillTotal 中列出所有customer 字段?
【问题讨论】:
标签: hibernate spring-data-jpa jpql