简体   繁体   English

jpa entitymanager - map 查询结果到嵌套的 dto 类中

[英]jpa entitymanager - map query result into nested dto classes

I'm using jpa EntityManager with hibernate in my java spring application.我在我的 java Z2A2D595E6ED9A0B234F0627B 应用程序中使用jpa EntityManager 和 hibernate Suppose I have a user entity like below:假设我有一个如下的用户实体:

public class User {
    private Long id;
    ...
    
    @ManyToOne
    private Address address
}

And I have Custom user dto object for passing into client:我有自定义用户 dto object 用于传递给客户端:

public class UserDTO {
    private Long id;
    private AddressDTO address;
    ...
}

And I have a UserRepository that exceute normal jpql query with EntityManager and Query .我有一个 UserRepository 可以使用EntityManagerQuery执行正常的 jpql 查询。

Note, I need to have custom dto, because my dto has some fields that does not exist in entity and must be calculated in query.注意,我需要自定义 dto,因为我的 dto 有一些字段在实体中不存在,必须在查询中计算。 Now my question: is there any way with EntityManager that map flat query result into my nested UserDTO?现在我的问题是: EntityManager 有没有办法将 map 平面查询结果放入我的嵌套 UserDTO? In fact, I need to map result of address in AdressDTO inside UserDto and so on.事实上,我需要 map 地址结果在 AdressDTO 里面 UserDto 等等。

Note: I want to use jpql not native sql query.注意:我想使用 jpql 而不是原生 sql 查询。

You can construct DTO right in JPQL.您可以直接在 JPQL 中构建 DTO。 Here is an example.这是一个例子。

select new your.package.UserDTO(u.id, a.country, a.city, a.street)
from User u join u.address a
where ...

Such query returns List<UserDTO> .此类查询返回List<UserDTO>

Of course UserDTO has to have appropriate constructor:当然UserDTO必须有适当的构造函数:

public UserDTO(Long id, String country, String city, String street){
   this.id = id;
   this.address = new AddressDTO(country, city, street);
}

You're on the right way.你走对了。

You really need to fetch User and then convert it to UserDTO.您确实需要获取用户,然后将其转换为 UserDTO。 Don't build DTO within your queries.不要在查询中构建 DTO。

For that conversion you need Java Mapper.对于该转换,您需要 Java 映射器。 I prefer MapStruct but there is a plenty of such tools (ModelMapper, Dozer etc).我更喜欢MapStruct ,但有很多这样的工具(ModelMapper、Dozer 等)。

MapStruct is smart enough to manage nested objects as well. MapStruct 也很聪明,可以管理嵌套对象。

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

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