How to use Explicit Map with Java 8 and ModelMapper?
They missed a step in this example, the addMappings
method they use is the addMappings
from TypeMap, not from ModelMapper
. You need to define a TypeMap
for your 2 objects. This way:
// Create your mapper
ModelMapper modelMapper = new ModelMapper();
// Create a TypeMap for your mapping
TypeMap<Order, OrderDTO> typeMap =
modelMapper.createTypeMap(Order.class, OrderDTO.class);
// Define the mappings on the type map
typeMap.addMappings(mapper -> {
mapper.map(src -> src.getBillingAddress().getStreet(),
OrderDTO::setBillingStreet);
mapper.map(src -> src.getBillingAddress().getCity(),
OrderDTO::setBillingCity);
});
An other way would be to use the addMappings
method from ModelMapper
. It does not use lambdas and takes a PropertyMap. It is short enough too:
ModelMapper modelMapper = new ModelMapper();
modelMapper.addMappings(new PropertyMap<Order, OrderDTO>() {
@Override
protected void configure() {
map().setBillingStreet(source.getBillingAddress().getStreet());
map().setBillingCity(source.getBillingAddress().getCity());
}
});
if the source and destination type are different. For example,
@Entity
class Student {
private Long id;
@OneToOne
@JoinColumn(name = "laptop_id")
private Laptop laptop;
}
And Dto ->
class StudentDto {
private Long id;
private LaptopDto laptopDto;
}
Here, the source and destination types are different. So, if your MatchingStrategies are STRICT, you won't able to map between these two different types. Now to solve this, Just simply put this below code in the constructor of your controller class or any class where you want to use ModelMapper->
private ModelMapper modelMapper;
public StudentController(ModelMapper modelMapper) {
this.modelMapper = modelMapper;
this.modelMapper.typeMap(Student.class, StudentDto.class).addMapping(Student::getLaptop, StudentDto::setLaptopDto);
}
That's it. Now you can use ModelMapper.map(source, destination) easily. It will map automatically
modelMapper.map(student, studentDto);