Issue
I have an User
class:
public class User {
private Long id;
private String name;
private String ssn;
private int age;
private double height;
private double weight;
}
public class UpdateUserDTO {
private String name;
private int age;
private double height;
private double weight;
}
The UpdateUserDTO
is used in the PUT request body to update the user's data. At least one of the fields is required to be not null in the UpdateUserDTO
instance, but the client can update as many as he wants, so I am expecting this instance to have a different number of not null values each time a new request is received.
I retrieve the User class (original data) from the database, and I want to map the not null fields from the UpdateUserDTO
to the User
class.
I don't want to do it using many if-else
statements.
Thanks in advance!
Solution
Assuming your first choice ModelMapper is still something you want to use, it should perfectly work for your case. The User class has to provide the required setName(String name)
method.
import org.modelmapper.ModelMapper;
public class ModelMapperExample {
public static void main(String[] args) {
User user = new User(); // simplified, retrieved from elsewhere
UpdateUserDTO updated = new UpdateUserDTO(); // simplified, retrieved from elsewhere
updated.setName("Paula");
ModelMapper modelMapper = new ModelMapper();
modelMapper.map(updated, user);
System.out.println(user.getName()); // prints Paula
}
}
See Javadoc for more information on this: http://modelmapper.org/javadoc/org/modelmapper/ModelMapper.html#map-java.lang.Object-java.lang.Object-
Answered By - swinkler
Answer Checked By - David Marino (JavaFixing Volunteer)