ModelMapper for simple mapping of objects


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, 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:

import org.modelmapper.ModelMapper;

public class MyApplicationConfig implements WebMvcConfigurer {

  public ModelMapper modelMapper() {
    return new ModelMapper();

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


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!

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.