有时候DTO与Model之间不一定是完全匹配上的,这个时候ModelMapper就不知道怎么处理,就需要我们手动处理两层之间的字段映射了。
<properties>
<modelmapper.version>3.1.0</modelmapper.version>
</properties>
...
<dependencies>
<dependency>
<groupId>org.modelmapper.extensions</groupId>
<artifactId>modelmapper-spring</artifactId>
<version>${modelmapper.version}</version>
</dependency>
</dependencies>
@Configuration
public class ModelMapperConfig {
@Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.typeMap(Order.class, OrderDTO.class).addMappings(mapper -> {
mapper.map(src -> src.getBillingAddress().getStreet(),
Destination::setBillingStreet);
mapper.map(src -> src.getBillingAddress().getCity(),
Destination::setBillingCity);
});
return modelMapper;
}
}