avatarSamuel Catalano

Summary

The provided content is a comprehensive guide on using ModelMapper in Java for object mapping, including how to get started, map objects, customize mappings, and implement different mapping strategies.

Abstract

The article "Guide to Object Mapping with ModelMapper in Java" introduces the ModelMapper library as a solution to the cumbersome task of object mapping in Java. It explains the benefits of using ModelMapper to simplify the process of transforming data between objects with different structures. The guide covers the initial setup for including ModelMapper in a Java project using Maven or Gradle, demonstrates basic object mapping with examples, and delves into advanced customization options such as custom field mappings and type converters. Additionally, it discusses various mapping strategies provided by ModelMapper, such as Strict, Loose, and Standard, to tailor the mapping behavior according to project needs. The article concludes by emphasizing the efficiency and flexibility gained by using ModelMapper, allowing developers to focus on core application functionality rather than boilerplate mapping code.

Opinions

  • The author believes that ModelMapper is a powerful and flexible library that can significantly reduce the amount of boilerplate code required for object mapping in Java.
  • The article suggests that ModelMapper's ability to handle custom field mappings and type conversions provides developers with a high degree of control over the mapping process.
  • The author endorses the use of ModelMapper's mapping strategies, particularly the Loose strategy, for its ability to map fields with different names and types, which can be very useful in real-world scenarios.
  • The article implies that adopting ModelMapper can enhance productivity and maintainability of Java codebases by abstracting away the complexities of manual object mapping.
  • The author encourages readers to support the publication by following it and suggests further reading through linked articles on related topics.
  • The author promotes an AI service, ZAI.chat, as a cost-effective alternative to ChatGPT Plus (GPT-4), indicating a belief in the value and performance of this service.

Guide to Object Mapping with ModelMapper in Java

Object mapping is a process of transforming data from one object to another. In Java, it can be a tedious task that requires a lot of boilerplate code to map data between two objects with different structures. Fortunately, there is a powerful library called ModelMapper that simplifies the object mapping process and provides a lot of flexibility in customizing the mapping behaviour.

In this article, we will introduce you to ModelMapper and show you how to use it to map between two objects in Java.

Getting Started with ModelMapper

To start using ModelMapper in your Java project, you need to add the ModelMapper library to your project. If you are using Maven, add the following dependency to your project’s pom.xml file:

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

If you are using Gradle, add the following to your build.gradle file:

implementation 'org.modelmapper:modelmapper:2.4.2'

After adding the ModelMapper library to your project, you can start using it to map between two objects with different structures.

Mapping Objects with ModelMapper

Let’s say you have two objects with different structures, and you want to map data between them. Here’s an example:

public class User {
    private String name;
    private int age;

    // constructor, getters, and setters
}

public class UserDTO {
    private String fullName;
    private int userAge;

    // constructor, getters, and setters
}

public class Main {
    public static void main(String[] args) {
        User user = new User("John", 30);
        ModelMapper modelMapper = new ModelMapper();
        UserDTO userDTO = modelMapper.map(user, UserDTO.class);
        System.out.println(userDTO.getFullName()); // Output: John
        System.out.println(userDTO.getUserAge()); // Output: 30
    }
}

In the above example, we have two objects User and UserDTO with different structures. The User object has fields name and age, while the UserDTO object has fields fullName and userAge. We use the ModelMapper instance to map the User object to UserDTO. The map() method takes two arguments: the source object and the destination object class.

When we run the main method, the output will be John and 30, which indicates that the mapping was successful.

Customizing Object Mapping

ModelMapper provides a lot of flexibility in customizing object mapping. You can specify custom field mappings, create type converters, and configure different mapping strategies.

Custom Field Mappings

Sometimes, you might need to map fields with different names between two objects. You can achieve this by specifying custom field mappings. Here’s an example:

modelMapper.typeMap(User.class, UserDTO.class)
  .addMappings(mapper -> {
      mapper.map(src -> src.getName(), UserDTO::setFullName);
      mapper.map(src -> src.getAge(), UserDTO::setUserAge);
  });

In the above example, we create a custom field mapping between the User and UserDTO objects. We use the typeMap() method to create a type mapping between the two objects, and then we use the addMappings() method to specify the custom field mappings.

Type Converters

ModelMapper provides a number of built-in type converters that can automatically convert data between different types. However, sometimes you might need to create your own type converters for custom data types. Here’s an example:

public class DateToStringConverter extends AbstractConverter<Date, String> {
    @Override
    protected String convert(Date source) {
        return source.toString();
    }
}

In the above example, we create a custom type converter that converts a Date object to a String. We extend the AbstractConverter class and implement the convert() method to perform the conversion.

We can register the custom type converter with the ModelMapper instance by calling the addConverter() method:

modelMapper.addConverter(new DateToStringConverter());

Once the custom type converter is registered, ModelMapper will automatically use it to convert between Date and String data types.

Mapping Strategies

ModelMapper provides several mapping strategies that can be used to customize the mapping behaviour. Some of the available strategies include Strict, Loose, and Standard.

For example, the Loose strategy allows mapping between fields with different names and types, while the Strict strategy enforces strict mapping rules and raises an exception when a mapping cannot be performed.

You can set the mapping strategy by calling the setMatchingStrategy() method on the ModelMapper instance:

modelMapper.getConfiguration()
  .setMatchingStrategy(MatchingStrategies.LOOSE);

In the above example, we set the mapping strategy to Loose, which allows mapping between fields with different names and types.

Conclusion

In this article, we have shown you how to use ModelMapper to map between two objects in Java. ModelMapper is a powerful library that simplifies the object mapping process and provides a lot of flexibility in customizing the mapping behaviour.

By using ModelMapper, you can avoid writing a lot of boilerplate code for object mapping, and focus on the core functionality of your application.

Thanks for reading.Happy learning 😄

Do support our publication by following it

Also refer to the following articles

Java
Modelmapper
Objects
Dto
Conversion
Recommended from ReadMedium