简体   繁体   中英

jpa entitymanager - map query result into nested dto classes

I'm using jpa EntityManager with hibernate in my java spring application. 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:

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

And I have a UserRepository that exceute normal jpql query with EntityManager and Query .

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. Now my question: is there any way with EntityManager that map flat query result into my nested UserDTO? In fact, I need to map result of address in AdressDTO inside UserDto and so on.

Note: I want to use jpql not native sql query.

You can construct DTO right in JPQL. 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> .

Of course UserDTO has to have appropriate constructor:

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. Don't build DTO within your queries.

For that conversion you need Java Mapper. I prefer MapStruct but there is a plenty of such tools (ModelMapper, Dozer etc).

MapStruct is smart enough to manage nested objects as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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