如何通过category_id为Product设置Category?Spring Boot报错求助
问题分析
报错核心原因:前端传的JSON里,category字段值是数字(比如1),Jackson试图把这个数字转成Category实体,但该实体没有接收整数参数的构造方法,导致反序列化失败。同时当前代码没正确利用category_id关联分类。
解决方案
1. 调整ProductDTO结构
DTO是用来接收前端请求数据的,没必要同时放Category实体和category_id,直接保留category_id即可:
public class ProductDTO { private Integer id; private String title; private BigDecimal price; private LocalDateTime createdAt; // 只留分类ID,用来接收前端传的分类标识 private Integer category_id; // 记得生成getter、setter方法 }
如果非得保留Category字段,给它加@JsonIgnore注解,让Jackson反序列化时忽略这个字段:
public class ProductDTO { private Integer id; private String title; // 反序列化时跳过这个字段,避免Jackson把数字转成Category对象 @JsonIgnore private Category category; private BigDecimal price; private LocalDateTime createdAt; private Integer category_id; // getter、setter方法 }
2. 修改ProductService逻辑,用category_id关联分类
注入CategoryRepository,通过传入的category_id查询对应的分类实体,再绑定到商品上:
public class ProductService { @Autowired ProductRepository productRepository; @Autowired ProductMapper productMapper; @Autowired CategoryRepository categoryRepository; // 新增注入分类仓库 public void addProduct(ProductDTO productDTO){ productDTO.setCreatedAt(LocalDateTime.now()); // 根据category_id查分类,不存在就抛异常(可自定义异常类型) Category category = categoryRepository.findById(productDTO.getCategory_id()) .orElseThrow(() -> new RuntimeException("指定分类不存在")); // 转成Product实体,手动设置分类 Product productEntity = productMapper.convertToEntity(productDTO); productEntity.setCategory(category); productRepository.save(productEntity); } }
3. 调整前端请求格式
确保前端传的JSON里带category_id字段,不要传category对象,示例:
{ "title": "测试商品", "price": 99.99, "category_id": 1 }
4. (可选)优化映射逻辑
如果用MapStruct这类工具做DTO转实体,确保convertToEntity方法只处理基础字段,category字段由Service手动设置,避免映射冲突。
额外提醒
- DTO要专注数据传输,别同时放实体对象和对应ID,容易搞混序列化逻辑。
- 查询分类时加异常处理,给前端返回明确的错误提示,避免空指针问题。
内容的提问来源于stack exchange,提问作者pavicevic
相关产品推荐
相关产品推荐

