spring - 映射基本 POJOS 的 ModelMapper 问题
问题描述
我有 2 个用于构建 json 对象的基本 POJO:
public class ProductCreateRequestModel {
private String name;
private double price;
private int qty;
private String imgPath;
private CategoryRequestCreateProductModel category;
}
public class CategoryRequestCreateProductModel {
private String name;
private String categoryKeyId;
}
基本上它允许我使用像这样的简单 json:
{
"name": "Pizza,
"price": 344.0,
"qty": 15,
"imgPath": "new/pathImage",
"category": {
"categoryKeyId": "23ume70Fu6yqyGUWfQkW110P4ko3gZ",
"name": "Starter"
}
}
我想发送这个 JSON 并持久化数据,我期望一个对象作为回报,我用这个 POJO 构建:
public class ProductRest {
private String productKeyId;
private String name;
private double price;
private int qty;
private String imgPath;
private CategoryRest category;
}
在我的控制器中,我只需要调用一个使用 PostMapping 的方法
@PostMapping(
consumes = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE },
produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }
)
public ProductRest createProduct(@RequestBody ProductCreateRequestModel productCreateRequestModel) throws Exception {
ProductRest returnValue = new ProductRest();
if(productCreateRequestModel.getName().isEmpty() || productCreateRequestModel.getPrice() <= 0)
throw new ApplicationServiceException(ErrorMessages.MISSING_REQUIRED_FIELDS.getErrorMessage());
ModelMapper modelMapper = new ModelMapper();
ProductDto productDto = modelMapper.map(productCreateRequestModel, ProductDto.class);
ProductDto createdProduct = productService.createProduct(productDto);
returnValue = modelMapper.map(createdProduct, ProductRest.class);
return returnValue;
}
我的服务层实际上并没有做任何特别的事情:
@Override
public ProductDto createProduct(ProductDto productDto) {
return productDto;
}
我的 DTO 层包含以下字段:
@Getter @Setter
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 availableQty;
private String imgPath;
private CategoryDto category = new CategoryDto();
}
@Getter @Setter
public class CategoryDto implements Serializable {
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private static final long serialVersionUID = 1L;
private long id;
private String categoryKeyId;
private String name;
private CategoryDto parentCategory;
private List<CategoryDto> subCategories;
private String parentCategoryKeyId;
private Long parentCategoryId;
}
在尝试运行此基本代码时,我收到一条错误消息:
java.lang.NumberFormatException:对于输入字符串:“23ume70Fu6yqyGUWfQkW110P4ko3gZ”
解决方案
推荐阅读
- php - 为 URL 创建 Cron 作业
- wordpress - 在 foreach 循环中显示 ACF 图像字段
- .net - ODATA 日期过滤器 - 生成与预期不同的 sql server 查询 - 导致性能不佳
- python - 检查 2 继续列表中的值
- c# - 无法在解决方案中创建新的 Prism 项目
- r - geom_step 以水平线段开始和结束
- postgresql - 是否需要使用多台计算机进行主从复制?
- php - SQL如何跳过列上的重复值
- python - 从 Odoo 控制器重定向时表单不安全
- html - Angular 9 Typescript 引用 node_modules 来修复 MIME 错误