You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot POST接口传关联实体ID反序列化失败如何解决

解决方案

问题根本原因:你直接使用Article实体类作为接口@RequestBody的接收参数,Jackson在解析JSON报文时,无法将报文中categoryOfArticle、authorOfArticle对应的数值直接转换为Category、Author类型的实体对象,因此抛出缺少对应构造方法的反序列化异常。你之前新增的authorId、categoryId字段不生效,是因为JSON报文中的key为categoryOfArticle/authorOfArticle和你新增的字段名不匹配,反序列化时无法完成赋值。

方案1:使用DTO接收请求参数(最推荐,符合分层规范)

该方案耦合度低,不会侵入实体类代码,是企业项目的通用实践。

  • 第一步:新增Article新增请求的DTO类
// ArticleAddDTO.java
import lombok.Data;

@Data
public class ArticleAddDTO {
    private String title;
    private Integer categoryOfArticle;
    private Integer authorOfArticle;
}
  • 第二步:修改Controller层接口,用DTO接收参数
@PostMapping("/article")
public ResponseEntity<Void> addArticle(@RequestBody ArticleAddDTO dto) {
    articleService.save(dto);
    return ResponseEntity.ok().build();
}
  • 第三步:修改Service层save方法逻辑
// ArticleServiceImpl.java
@Override
public void save(ArticleAddDTO dto) {
    // 1. 构建Article实例
    Article article = new Article();
    article.setTitle(dto.getTitle());
    // 2. 根据ID查询关联实体
    Category category = categoryMapper.selectById(dto.getCategoryOfArticle());
    Author author = authorMapper.selectById(dto.getAuthorOfArticle());
    // 3. 赋值关联属性
    article.setCategoryOfArticle(category);
    article.setAuthorOfArticle(author);
    // 4. 保存Article
    articleMapper.insert(article);
}

方案2:给关联实体加带ID参数的构造方法(适合不想新增DTO的场景)

直接在Category和Author实体类中新增带ID参数的构造方法,加上@JsonCreator注解让Jackson反序列化时自动调用该构造方法生成实例:

// Category类新增构造方法
@JsonCreator
public Category(Integer id) {
    this.id = id;
}
// 必须保留原有无参构造方法
public Category() {}

// Author类同理新增
@JsonCreator
public Author(Integer id) {
    this.id = id;
}
public Author() {}

配置完成后可以直接用Article实体接收请求参数,此时反序列化会自动生成仅赋值了ID的Category和Author实例,你在Service层中直接用这两个ID查询完整实体再赋值即可。

方案3:修改Article实体类的setter方法适配

在Article类中新增对应数值类型的setter方法,适配JSON的字段名:

// Article类新增
public void setCategoryOfArticle(Integer id) {
    Category category = new Category();
    category.setId(id);
    this.categoryOfArticle = category;
}

public void setAuthorOfArticle(Integer id) {
    Author author = new Author();
    author.setId(id);
    this.authorOfArticle = author;
}

该方案不需要修改其他层代码,直接可以直接用Article实体接收参数即可。

内容的提问来源于stack exchange,提问作者Smetana Po Aktsii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:27:00