简体   繁体   English

HQL查询到复杂的DTO

[英]HQL query to complex DTO

I have an issue with mapping HQL query to complex DTO. 将HQL查询映射到复杂DTO时遇到问题。 By complex DTO I mean DTO that composites another DTOs / collection DTOs. 复杂的DTO是指将另一个DTO /集合DTO组合在一起的DTO。 I tried to find solution but didn't find anything that can suit my requirements. 我试图找到解决方案,但没有找到任何适合我要求的东西。 For instance there is a DTO (I omit properties for simplicity): 例如,有一个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
  }

}

The HQL lets to create DTO object through constructor by passing columns from result set as parameters. 通过将结果集中的列作为参数传递,HQL允许通过构造函数创建DTO对象。 Is it possible to create subqueries or smth. 是否可以创建子查询或smth。 Else to fetch data in collection and then pass it as arguments in main DTO? 还可以获取集合中的数据,然后将其作为主DTO中的参数传递吗? It looks that it is impossible but maybe I missed something. 看来这是不可能的,但也许我错过了一些东西。

Otherwise there is only the way to do that is to fetch data in separate HQL queries and then create main DTO as plain Java object. 否则,唯一的方法就是在单独的HQL查询中获取数据,然后将主DTO创建为纯Java对象。 If anyone has alternative ideas how to do that - please share your ideas. 如果有人有其他想法,该怎么做-请分享您的想法。

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

FROM Consignment cons JOIN FETCH cons.orderData ord

I created Blaze-Persistence Entity Views for exactly that use case. 我正是为该用例创建了Blaze-Persistence实体视图 You essentially define DTOs for JPA entities as interfaces and apply them on a query. 您实际上将JPA实体的DTO定义为接口,并将其应用于查询。 It supports mapping nested DTOs, collection etc., essentially everything you'd expect and on top of that, it will improve your query performance as it will generate queries fetching just the data that you actually require for the DTOs. 它支持映射嵌套的DTO,集合等,本质上是您期望的所有内容,此外,它还将提高查询性能,因为它将生成查询,仅提取DTO实际需要的数据。

The entity views for you example could look like this 您的实体视图示例如下所示

@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
}

Querying could look like this 查询可能看起来像这样

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM