【问题标题】:JPQL eagerly fetch elementJPQL 急切地获取元素
【发布时间】: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


    【解决方案1】:

    如果您将实体别名传递给 JPQL 中的构造函数,Hibernate 必须实现整个对象,因此它会以某种方式获取所有字段。据我所知,Hibernate 中构造函数表达式的当前实现将始终在传递实体别名时传入代理,因此您看到的次要负载是由于 Hibernate 加载状态所致。如果您只想获取实际需要的字段,则需要明确列出它们。

    您可能还喜欢Blaze-Persistence Entity Views 提供的服务。

    我创建了该库以允许在 JPA 模型和自定义接口或抽象类定义模型之间轻松映射,例如 Spring Data Projections on steroids。这个想法是您按照自己喜欢的方式定义目标结构(域模型),并通过 JPQL 表达式将属性(getter)映射到实体模型。

    使用 Blaze-Persistence Entity-Views 的用例的 DTO 模型可能如下所示:

    @EntityView(Customer.class)
    public interface CustomerWithBillTotal {
        @IdMapping("sq")
        Integer getId();
        String getCustomerName();
        // Other customer mappings you need...
    
        // Assuming you have a one-to-many association named "bills" in Customer
        @Mapping("COALESCE(SUM(bills.amount), 0)")
        // You can also use this if you don't have that association
        // @Mapping("COALESCE(SUM(Bills[customer.sq = VIEW(sq) AND periodFrom <= :periodFrom and periodTo >= :periodTo].amount), 0)")
        BigDecimal getAmount();
    }
    

    查询是将实体视图应用于查询的问题,最简单的就是通过 id 进行查询。

    CustomerWithBillTotal a = entityViewManager.find(entityManager, CustomerWithBillTotal.class, id);

    Spring Data 集成让您可以像使用 Spring Data Projections 一样使用它:https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

       List<CustomerWithTotal> findByDepartmentId(Long departmentId, @OptionalParam("periodFrom") LocalDate from, @OptionalParam("periodTo") LocalDate to);
    

    【讨论】:

      猜你喜欢
      • 2016-02-19
      • 1970-01-01
      • 2011-06-24
      • 1970-01-01
      • 1970-01-01
      • 2012-11-02
      • 2018-08-17
      • 2014-06-23
      • 2012-12-17
      相关资源
      最近更新 更多