'How to convert nested objects into nested DTOs using ModelMapper?
I am facing issue when I am trying to use ModelMapper to convert nested java objects into nested DTO's. Getting null for child dto's in parent dto object. Following are the code snippets.
Entity Classes :
public class User {
private String name;
private Address address;
private Product product;
}
public class Address {
private String area;
private String city;
}
public class Product {
private Integer productId;
private String productName;
private Double productPrice;
}
DTO's Classes :
public class UserDTO {
private String name;
private AddressDTO address;
private ProductDTO product;
}
public class AddressDTO {
private String area;
private String city;
}
public class ProductDTO {
private Integer productId;
private String productName;
private Double productPrice;
}
here is the mapper code :
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
UserDTO userDTO = mapper.map(user, UserDTO.class);
System.out.println("Output User DTO : " + userDTO );
Output :
Output User DTO : UserDTO [name=xyz, address=null, product=null]
Here I want to convert User entity into UserDTO dto. I am getting null values for address and product DTO's. What exactly I am missing here ? Does anyone have any idea ?
Note : I have added getters, Setters and toString() methods in entity and DTO's.
Solution 1:[1]
Here I found solution for nested DTO to Entity and vice versa conversions, I was missing some ModelMapper configurations that I have added below.
mapper.getConfiguration()
.setFieldMatchingEnabled(true)
.setFieldAccessLevel(AccessLevel.PRIVATE)
.setMatchingStrategy(MatchingStrategies.STANDARD);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Shubham Bhosale. |