【问题标题】:HQL query to complex DTO对复杂 DTO 的 HQL 查询
【发布时间】:2018-07-08 14:07:34
【问题描述】:

我在将 HQL 查询映射到复杂 DTO 时遇到问题。我所说的复杂 DTO 是指组合另一个 DTO / 集合 DTO 的 DTO。我试图找到解决方案,但没有找到任何可以满足我要求的东西。例如有一个 DTO(为简单起见,我省略了属性):

public class Consignment {

  private List<OrderData> orderData;
  private List<AttributesData> attributesData;
  private CostData costData;

  public Consignment(List<OrderData> orderData, List<AttributesData> attributesData, CostData costData) {
    //setting fields
  }

}

HQL 允许通过构造函数通过将结果集中的列作为参数传递来创建 DTO 对象。是否可以创建子查询或 smth.否则要在集合中获取数据,然后将其作为参数传递给主 DTO?看起来这是不可能的,但也许我错过了什么。

否则,唯一的方法是在单独的 HQL 查询中获取数据,然后将主 DTO 创建为纯 Java 对象。如果有人有其他想法如何做到这一点 - 请分享您的想法。

【问题讨论】:

标签: java hibernate hql dto


【解决方案1】:

您可以像这样在同一查询中获取其他数据:

FROM Consignment cons JOIN FETCH cons.orderData ord

【讨论】:

    【解决方案2】:

    我为那个用例创建了Blaze-Persistence Entity Views。您基本上将 JPA 实体的 DTO 定义为接口并将它们应用于查询。它支持映射嵌套 DTO、集合等,基本上是您所期望的一切,最重要的是,它会提高您的查询性能,因为它会生成查询,只获取 DTO 实际需要的数据。

    您示例的实体视图可能如下所示

    @EntityView(ConsignmentEntity.class)
    interface Consignment {
      List<OrderData> getOrderData();
      List<AttributesData> getAttributesData();
      CostData getCostData();
    }
    
    @EntityView(OrderDataEntity.class)
    interface OrderData {
      // attributes of OrderDataEntity that you need
    }
    @EntityView(AttributesDataEntity.class)
    interface AttributesData {
      // attributes of AttributesDataEntity that you need
    }
    @EntityView(CostDataEntity.class)
    interface CostData {
      // attributes of CostDataEntity that you need
    }
    

    查询可能如下所示

    List<Consignment> dtos = entityViewManager.applySetting(
      EntityViewSetting.create(Consignment.class),
      criteriaBuilderFactory.create(em, ConsignmentEntity.class)
    ).getResultList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 2020-12-05
      相关资源
      最近更新 更多