我在映射到另一个对象列表时在对象列表中获取空值。
Dto Classes :(考虑在dto类中生成的getter / setter)
public class Customer {
private Long id;
private String name;
private Collection<OrderItem> orderItems;
}
public class OrderItem {
private String name;
private Long quantity;
}
public class CustomerDto {
public Long id;
public String customerName;
public List<OrderItemDto> orders;
}
public class OrderItemDto {
public String name;
public Long quantity;
}
映射器:
@Mapper(uses = { OrderItemMapper.class })
public interface CustomerMapper {
CustomerMapper MAPPER = Mappers.getMapper( CustomerMapper.class );
@Mappings({
@Mapping(source = "orders", target = "orderItems"),
@Mapping(source = "customerName", target = "name")
})
Customer toCustomer(CustomerDto customerDto);
@InheritInverseConfiguration
CustomerDto fromCustomer(Customer customer);
}
@Mapper
public interface OrderItemMapper {
OrderItemMapper MAPPER = Mappers.getMapper(OrderItemMapper.class);
@Mappings({
@Mapping(source = "name", target = "name"),
@Mapping(source = "quantity", target = "quantity")
})
OrderItem toOrder(OrderItemDto orderItemDto);
@InheritInverseConfiguration
OrderItemDto fromOrder(OrderItem orderItem);
}
测试类:
public class App {
public static void main(String[] args) {
CustomerDto customerDto = new CustomerDto();
customerDto.id = 10L;
customerDto.customerName = "Filip";
OrderItemDto order1 = new OrderItemDto();
order1.name = "Table";
order1.quantity = 2L;
ArrayList<OrderItemDto> tmpOrders = new ArrayList<OrderItemDto>();
tmpOrders.add(order1);
customerDto.setOrders(tmpOrders);
for (OrderItemDto order : customerDto.getOrders()) {
System.out.println(" order items = " + order.toString());
}
Customer customer = CustomerMapper.MAPPER.toCustomer(customerDto);
System.out.println(" id ==== " + customer.getId());
System.out.println("getName == " + customer.getName());
for (OrderItem order : customer.getOrderItems()) {
System.out.println(" order items = " + order.toString());
}
}
}
我得到的输出为:
order items = name = Table , qty = 2
id ==== 10
getName ==Filip
order items = name = null , qty = null
这里我得到Order Object(name,qty)的空值
我不明白这段代码中缺少什么。