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.
Join the DZone community and get the full member experience.
Join For FreeAs 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.
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String firstName;
private String lastName;
private List<String> subscriptions;
private String country;
private String city;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserDTO {
private String firstName;
private String secondName;
private String subscriptions;
private LocationDTO location;
}
@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.
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.
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.
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.
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.
// 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
.
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
:
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
.
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
@Data
@Builder
public class UserWithBuilder {
private final String firstName;
private final String lastName;
}
@Data
@Builder
public final class UserWithBuilderDTO {
private final String firstName;
private final String secondName;
}
Converter
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.
Opinions expressed by DZone contributors are their own.
Comments