【问题标题】:How to convert list inside JPA query to DTO如何将 JPA 查询中的列表转换为 DTO
【发布时间】:2022-09-30 20:53:52
【问题描述】:

需要将帐户列表转换为 accountDto。问题是如何?

@Query(\"SELECT ac.account FROM Academy ac WHERE ac.id = :uuid\")
fun findAcademyAccountsById(uuid: UUID, pageable: Pageable): List<AccountDto>

    标签: hibernate jpa spring-data-jpa spring-data hql


    【解决方案1】:

    取决于AccountAccountDto 的外观以及您正在寻找什么样的性能。您可以手动或使用映射器将实体对象转换为 Java 代码中的 DTO 对象,例如地图结构。

    我认为这是Blaze-Persistence Entity Views 的完美用例。

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

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

    @EntityView(Account.class)
    public interface AccountDto {
        @IdMapping
        Long getId();
        String getName();
    }
    

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

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

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

    Page<AccountDto> findAll(Pageable pageable);
    

    最好的部分是,它只会获取实际需要的状态!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 2021-09-08
      相关资源
      最近更新 更多