ModelMapper for simple mapping of objects

ModelMapper
Difficulty

Today we will see how to implement a ModelMapper that allows us, for example, to transform an object with many properties into a smaller object with fewer properties. This transformation can be useful for example when we need leaner objects, perhaps in a list, or when we want to expose only some properties of an object, leaving the others hidden in logic.

We have this 2 objects:

class FullDTO {
  long id;
  String title;
  String author;
  String email;
  String password;
  String webSite;
  int hiddenInformation;
  boolean isForAdmin;
  
  // assume getters and setters
}
class LightDTO {
  long id;
  String title;
  String author;
  
  // assume getters and setters
}


In the class that needs mapping we can create a mapping method and use it ( mapToLight() ):

import org.modelmapper.ModelMapper;

class UsingModelMapper {
  @Autowired private ModelMapper modelMapper;

  public LightDTO mapToLight(FullDTO fullDTO) {
    return modelMapper.map(aSource, LightDTO.class);
  }
}


Now we need a ModelMapper bean to be wired for statically import it in all our application.
To configure ModelMapper in the application:

// MyBEConfig.java
import org.modelmapper.ModelMapper;

@Configuration
@EnableWebMvc
public class MyApplicationConfig implements WebMvcConfigurer {

  @Bean
  public ModelMapper modelMapper() {
    return new ModelMapper();
  }
}


Let’s not forget to import the library we need. To install ModelMapper with Maven, we can say:

    <dependency>
        <groupId>org.modelmapper</groupId>
        <artifactId>modelmapper</artifactId>
        <version>2.3.2</version>
    </dependency>


If you haven’t Spring Boot you can use it creating a new ModelMapper() object but prefear the first method:

ModelMapper modelMapper = new ModelMapper();


That’s all for now.
Try it at home!

0
Be the first one to like this.
Please wait...

Leave a Reply

Thanks for choosing to leave a comment.
Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published.
Please do NOT use keywords in the name field. Let's have a personal and meaningful conversation.