我有其余的模型用于构建发送的JSON。
休息模式
@Getter @Setter
@ToString
public class OrderRequestModel {
private String orderKeyId;
private String paymentMode;
private double totalAmount;
private List<ProductRequestModel> orderProducts;
private UserDetailsRequestModel seller;
private Date createdAt;
}
ProductRequestModel相似
@Getter @Setter
@ToString
public class ProductRequestModel {
private String productKeyId;
private String name;
private double price;
private int qty;
private String imgPath;
private CategoryRequestModel category;
}
我将模型传递给与数据库有关的DTO层(它们包含一个长ID):
@Getter @Setter
@ToString
public class OrderDto implements Serializable {
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private static final long serialVersionUID = 1L;
private Long id;
private String orderKeyId;
private String paymentMode;
private double totalAmount;
private List<ProductDto> orderProducts;
private UserDto seller;
private Date createdAt;
}
和我的ProductDto:
@Getter @Setter
@ToString
public class ProductDto implements Serializable {
// ommit this member and do not generate getter / setter
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private static final long serialVersionUID = 1L;
private Long id;
private String productKeyId;
private String name;
private double price;
private int qty;
private String imgPath;
private CategoryDto category = new CategoryDto();
}
当我尝试将OrderDto映射到关联的模型时,我会隐式地进行操作:
OrderDto orderDto = modelMapper.map(orderRequestModel, OrderDto.class);
理论上,模型中的orderKeyId应该与其Dto中的等效项匹配。不幸地,它返回一个错误:
Converter org.modelmapper.internal.converter.NumberConverter@3e36f4cc failed to convert java.lang.String to java.lang.Long.
Caused by: org.modelmapper.MappingException: ModelMapper mapping errors:
我确实需要DTO中的ID,因为如果要进行更新,请使用“ id”
答案 0 :(得分:1)
此问题是由于映射策略引起的。我们可以将映射策略设置为STRICT,以便从源对象属性映射到目标对象属性时,仅映射那些在属性名称及其数据类型上完全匹配的属性。下面是一个示例。
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration()
.setMatchingStrategy(MatchingStrategies.STRICT);
}
仅供参考: http://modelmapper.org/user-manual/configuration/#matching-strategies