对象映射工具很多,modelmapper 是另外一个不错的选择
特性
- 智能,大部分已经帮助大家解决了映射处理
- 便于代码重构
- 基于约定
- 可扩展
参考使用
具体源码可以参考官方文档
- 源模型
- 目的
@Data
public class OrderDTO {
private String customerFirstName;
private String customerLastName;
private String billingStreet;
private String billingCity;
}
- 测试
public class Test {
@org.junit.Test
public void demo(){
ModelMapper modelMapper = new ModelMapper();
Order order= new Order();
Customer customer = new Customer();
Name name = new Name();
name.setFirstName("dalong");
name.setLastName("demoapp");
customer.setName(name);
order.setCustomer(customer);
Address address = new Address();
address.setCity("beijing");
address.setStreet("beijing");
order.setBillingAddress(address);
OrderDTO orderDTO = modelMapper.map(order, OrderDTO.class);
assertEquals(order.getCustomer().getName().getFirstName(), orderDTO.getCustomerFirstName());
assertEquals(order.getCustomer().getName().getLastName(), orderDTO.getCustomerLastName());
assertEquals(order.getBillingAddress().getStreet(), orderDTO.getBillingStreet());
assertEquals(order.getBillingAddress().getCity(), orderDTO.getBillingCity());
}
}
说明
当然modelmapper 也提供了方便的周边集成,比如与数据库访问的,对于json 的处理也是支持的,算是一个很不错的工具包
参考资料
http://modelmapper.org/getting-started/