Home > Mobile >  jpa entitymanager - map query result into nested dto classes
jpa entitymanager - map query result into nested dto classes

Time:12-06

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.

CodePudding user response:

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);
}

CodePudding user response:

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.

  • Related