简介
项目中经常需要将Model和DTO互转,产生很多getXXX/setXXX
的模板化代码。使用ModelMapper可以简化转换步骤。
官网
http://modelmapper.org/
添加依赖
1 2 3 4 5
| <dependency> <groupId>org.modelmapper</groupId> <artifactId>modelmapper</artifactId> <version>2.3.0</version> </dependency>
|
对象示例
源对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Order { Customer customer; Address billingAddress; }
class Customer { Name name; }
class Name { String firstName; String lastName; }
class Address { String street; String city; }
|
目标对象:
1 2 3 4 5 6 7
| class OrderDTO { String customerFirstName; String customerLastName; String billingStreet; String billingCity; }
|
自动转换
1 2
| ModelMapper modelMapper = new ModelMapper(); OrderDTO orderDTO = modelMapper.map(order, OrderDTO.class);
|
自定义转换
1 2 3 4 5 6
| modelMapper.typeMap(Order.class, OrderDTO.class).addMappings(mapper -> { mapper.map(src -> src.getBillingAddress().getStreet(), Destination::setBillingStreet); mapper.map(src -> src.getBillingAddress().getCity(), Destination::setBillingCity); });
|
转换配置
ModelMapper有Standard、Loose、Strict 3种模式:
1
| modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
|
参考文档:
http://modelmapper.org/user-manual/configuration/#matching-strategies
转换校验
assert手工校验:
1
| assertEquals(order.getCustomer().getName().getFirstName(), orderDTO.getCustomerFirstName());
|
ModelMapper自动校验:
1 2 3
| modelMapper.createTypeMap(Order.class, OrderDTO.class); modelMapper.addMappings(new OrderMap()); modelMapper.validate();
|