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

Similar Reads

What is DTO?

DTO stands for Data Transfer Object, these are the objects that move from one layer to another layer. DTO can be also used to hide the implementation detail of database layer objects. ModelMapper is a maven library that is used for the conversion of entity objects to DTO and vice-versa....

How to Use ModelMapper in Maven?

If you are using Maven then just add the modelmapper library as a dependency...

How to Map?

Basic Syntax of ModelMapper.map() Method:...

Example Spring Boot Project Step by Step

...

Contact Us