Basics Of ModelMapper

Published On: 25 August 2022.By .
  • Digital Engineering

Today, we are going to look at a basic overview of ModelMapper in a spring boot application.

Basically, Modelmapper is a object mapping library which is used for mapping to map DTOs into entities and vice-versa.
We are going to utilise a package called ModelMapper to map DTOs into entities and vice versa without having to create laborious/boilerplate code. By automatically calculating how one object model translates to another, ModelMapper aims to make object mapping simple.

This library supports an alot of options to speed up the mapping process and is fairly powerful, but it also emphasises convention over configuration by offering a default approach that works in most situations.

How It works?

ModelMapper consists of two distinct processes: the matching process, which matches the properties of a source and destination type, and the mapping process, which converts matched property values from a source to a destination object. Here is a more detailed explanation of these procedures.

  1. Matching Process:  Which source and destination properties match each other is determined by the matching process, which makes use of conventions set up in a ModelMapper or TypeMap. To discover source to destination matches, the procedure first identifies appropriate attributes, modifies and tokenizes their names, and then uses those tokens.

  2. Maping Process:  The mapping will take place in accordance with the Mappings specified in the TypeMap if there is a TypeMap for the source and destination types. If a Converter is available, and it can convert the source object to the desired type, mapping will take place via the Converter otherwise.

Getting Started
For starting with modelmapper in spring boot, you need to add the below dependency in pom.xml file:

Now Let’s start with Mapping. Suppose you are having following source model

Now, you are having a following requestDto

We can use ModelMapper to implicitly map an passBook instance to a new PassBookDTO:

And we can test that properties are mapped as expected:

Thus! We’ve learned how to map objects with safety and ease.
Some Learning Resources

  1. ModelMapper 
  2. Blog


Related content

Got an Idea?

Let’s create a better tomorrow together