取决于Account 和AccountDto 的外观以及您正在寻找什么样的性能。您可以手动或使用映射器将实体对象转换为 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);
最好的部分是,它只会获取实际需要的状态!