How to Map?
Basic Syntax of ModelMapper.map() Method:
public <D> D map(Object source, Class<D> destinationType) {
Assert.notNull(source, "source");
Assert.notNull(destinationType, "destinationType");
return this.mapInternal(source, (Object)null, destinationType, (String)null);
}
Let’s understand this map() with a simple example.
Example: Let’s say we have two object models one is the source and the other is the destination.
Source Model:
Java
// Assume getters and setters on each class class Employee { String name; String gender Address homeAddress; } class Address { String city; int pin; } |
Destination Model:
Java
// Assume getters and setters class EmployeeDTO { String name; String gender; String homeCity; int homePin; } |
By using ModelMapper.map() method we can implicitly map an Employee instance to a new EmployeeDTO
ModelMapper modelMapper = new ModelMapper();
EmployeeDTO employeeDTO = modelMapper.map(employee, EmployeeDTO.class);
If you are using Spring then you can also write the code in this way
@Autowired
private ModelMapper modelMapper;
EmployeeDTO employeeDTO = modelMapper.map(employee, EmployeeDTO.class);
Note: Reference article Spring @Autowired Annotation
How to Use ModelMapper in Spring Boot with Example Project?
ModelMapper is an intelligent, refactoring safe object mapping library that automatically maps objects to each other. The goal of ModelMapper is to make object mapping easy, by automatically determining how one object model maps to another, based on conventions. Some of the cool features of ModelMapper are:
- Intelligent
- Refactoring Safe
- Convention Based
- Extensible
Contact Us