DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Implementing Low-Code Data Mapping in Java
  • IntelliJ and Java Spring Microservices: Productivity Tips With GitHub Copilot
  • Java 21 Record and Pattern Matching: Master Data-Oriented Programming[Video]
  • Comparing ModelMapper and MapStruct in Java: The Power of Automatic Mappers

Trending

  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  • Ethical AI in Agile
  • Performing and Managing Incremental Backups Using pg_basebackup in PostgreSQL 17
  • Concourse CI/CD Pipeline: Webhook Triggers
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. My ModelMapper Cheat Sheet

My ModelMapper Cheat Sheet

Code samples of ModelMapper use cases such as adding custom mapping, saving custom mapping, and custom mapping with the builder pattern.

By 
Max Stepovyi user avatar
Max Stepovyi
·
Jan. 18, 24 · Code Snippet
Likes (2)
Comment
Save
Tweet
Share
4.1K Views

Join the DZone community and get the full member experience.

Join For Free

As the title says, this article will list my cheat sheet for ModelMapper. It will not provide any deep-dive tutorials or fancy descriptions, just some use cases.

Models Used for This Article

Any time you see User, UserDTO, LocationDTO in the code, refer to this section.

Java
 
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String firstName;
    private String lastName;
    private List<String> subscriptions;
    private String country;
    private String city;
}
Java
 
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserDTO {
    private String firstName;
    private String secondName;
    private String subscriptions;
    private LocationDTO location;
}
Java
 
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LocationDTO {
    private String country;
    private String city;
}


Basic typeMap Usage and addMapping

Use typeMap instead of createTypeMap when custom mapping is needed.

Example of how to map the lastName field to the secondName field.

Java
 
public UserDTO convert(User user) {
    return modelMapper.typeMap(User.class, UserDTO.class)
            .addMapping(User::getLastName, UserDTO::setSecondName)
            .map(user);
}


The Actual createTypeMap and getTypeMap Usage

If you use createTypeMap, ensure to use getTypeMap. It is easy to forget, as everyone provides an example with createTypeMap, but calling it twice will throw an exception.

Java
 
public class CreateTypeMapConverter {

    private final ModelMapper modelMapper;

    public CreateTypeMapConverter(ModelMapper modelMapper) {
        this.modelMapper = modelMapper;
        // can be moved to a configuration class
        var typeMap = modelMapper.createTypeMap(User.class, UserDTO.class);
        typeMap.addMapping(User::getLastName, UserDTO::setSecondName);
    }

    public UserDTO convert(User user) {
        return modelMapper.getTypeMap(User.class, UserDTO.class).map(user);
    }
}


And it is always possible to do it lazily.

Java
 
public UserDTO convert(User user) {
    var typeMap = modelMapper.getTypeMap(User.class, UserDTO.class);
    if (typeMap == null) {
        typeMap = modelMapper.createTypeMap(User.class, UserDTO.class);
        typeMap.addMapping(User::getLastName, UserDTO::setSecondName);
    }
    return typeMap.map(user);
}


Adding Mapping for Setter With Converter or Use using

Here is an example of how to convert List to String with typeMap before we set this value to the DTOs setter. For this, we call using with our converter logic.

Java
 
public UserDTO convertWithUsing(User user) {
    return modelMapper.typeMap(User.class, UserDTO.class)
            .addMappings(mapper -> {
                mapper.map(User::getLastName, UserDTO::setSecondName);
                mapper.using((MappingContext<List<String>, String> ctx) -> ctx.getSource() == null ? null : String.join(",", ctx.getSource()))
                        .map(User::getSubscriptions, UserDTO::setSubscriptions);
            })
            .map(user);
}


The same will work with any entity that requires custom conversion before setter.

ModelMapper Does Not Support Converting in addMapping

In the code sample, the value in the setter will be null, so we should avoid using addMapping to convert anything.

Java
 
// will throw NPE as o is null
public UserDTO addMappingWithConversion(User user) {
    return modelMapper.typeMap(User.class, UserDTO.class)
            .addMapping(User::getLastName, UserDTO::setSecondName)
            // o is null
            .addMapping(User::getSubscriptions, (UserDTO dest, List<String> o) -> dest.setSubscriptions(String.join(",", o)))
            .map(user);
}


But ModelMapper Supports Nested Setter

Example of mapping country and city fields to the nested object LocationDTO.

Java
 
public UserDTO convertNestedSetter(User user) {
    return modelMapper.typeMap(User.class, UserDTO.class)
            .addMapping(User::getLastName, UserDTO::setSecondName)
            .addMapping(User::getCountry, (UserDTO dest, String v) -> dest.getLocation().setCountry(v))
            .addMapping(User::getCity, (UserDTO dest, String v) -> dest.getLocation().setCity(v))
            .map(user);
}


Using preConverter and postConverter

Use when left with no choice or when conditionally needed to change the source or destination, but it’s hard or not possible with using.

Here is a super simplified example for preConverter:

Java
 
public UserDTO convertWithPreConverter(User user) {
    return modelMapper.typeMap(User.class, UserDTO.class)
            .setPreConverter(context -> {
                context.getSource().setFirstName("Joe");
                return context.getDestination();
            })
            .addMapping(User::getLastName, UserDTO::setSecondName)
            .map(user);
}


The same logic is for postConverter.

Java
 
public UserDTO convertWithPostConverter(User user) {
    return modelMapper.typeMap(User.class, UserDTO.class)
            .setPostConverter(context -> {
                var location = new LocationDTO(context.getSource().getCountry(), context.getSource().getCity());
                context.getDestination().setLocation(location);
                return context.getDestination();
            })
            .addMapping(User::getLastName, UserDTO::setSecondName)
            .map(user);
}


Using With Builder

For immutable entities that use the builder pattern.

Model

Java
 
@Data
@Builder
public class UserWithBuilder {
    private final String firstName;
    private final String lastName;
}
Java
 
@Data
@Builder
public final class UserWithBuilderDTO {
    private final String firstName;
    private final String secondName;
}


Converter

Java
 
public class BuilderConverter {

    private final ModelMapper modelMapper;

    public BuilderConverter(ModelMapper modelMapper) {
        this.modelMapper = modelMapper;
        var config = modelMapper.getConfiguration().copy()
                .setDestinationNameTransformer(NameTransformers.builder())
                .setDestinationNamingConvention(NamingConventions.builder());
        var typeMap = modelMapper.createTypeMap(UserWithBuilder.class, UserWithBuilderDTO.UserWithBuilderDTOBuilder.class, config);
        typeMap.addMapping(UserWithBuilder::getLastName, UserWithBuilderDTO.UserWithBuilderDTOBuilder::secondName);

    }

    public UserWithBuilderDTO convert(UserWithBuilder user) {
        return modelMapper.getTypeMap(UserWithBuilder.class, UserWithBuilderDTO.UserWithBuilderDTOBuilder.class)
                .map(user).build();
    }
}


But if all entities use the builder pattern, the configuration can be set up globally.

The full source code for this article can be found on GitHub.

Builder pattern GitHub Java (programming language) Data mapping

Opinions expressed by DZone contributors are their own.

Related

  • Implementing Low-Code Data Mapping in Java
  • IntelliJ and Java Spring Microservices: Productivity Tips With GitHub Copilot
  • Java 21 Record and Pattern Matching: Master Data-Oriented Programming[Video]
  • Comparing ModelMapper and MapStruct in Java: The Power of Automatic Mappers

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!