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

Spring Boot如何从请求体获取JSON插入关联关系字段?

问题根源分析

你遇到的外键字段为null的问题和是否用路径变量传递无关,核心原因有2个:

  1. Friend实体类没有映射friends表里的外键字段,JSON反序列化时找不到对应属性,值直接被丢弃
  2. 你当前直接保存Friend对象的逻辑,没有维护Pet和Friend的关联关系,JPA不会自动填充外键值

解决方案

第一步:调整实体类配置

首先修改Pet类的关联注解,把外键字段名改成你后续查询需要的pet_id,符合你的业务需求:

@JsonIgnore
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "pet_id", referencedColumnName = "pet_id") // 修改外键字段名
private List<Friend> friendsList = new ArrayList<>();

然后修改Friend实体类,补充外键字段的映射和对应的getter/setter:

@Entity
@Table(name = "friends")
public class Friend {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "pet_friend_uid", nullable = false)
    private int petFriendUid;

    @Column(name = "pet_id") // 新增外键字段映射
    private Integer petId;

    @Column(name = "friend_id")
    private int friendId;

    // 原有构造方法保留,补充petId的getter和setter
    public Integer getPetId() {
        return petId;
    }

    public void setPetId(Integer petId) {
        this.petId = petId;
    }

    // 原有其他getter保留
}

第二步:调整请求结构

不需要用路径变量,直接把petId放在请求体里即可,请求JSON修改为:

{
    "petId": 3,
    "friendId": 111
}

现在发送请求,friends表的pet_id和friend_id字段都会正常存入值,你后续用SELECT * FROM friends WHERE pet_id = 123就可以正常查询好友列表。


可选优化(更符合JPA规范的写法)

如果不想在Friend类里定义petId字段,可以通过维护关联关系的方式实现,逻辑如下:

  1. 注入PetRepository到你的Controller或者Service里
  2. 先根据请求里的petId查询出对应的Pet实体
  3. 新建Friend对象设置friendId,加到Pet的friendsList中
  4. 保存Pet实体,JPA会自动填充friends表的外键值

Controller修改示例:

@PostMapping
public ResponseEntity<Friend> saveFriend(@RequestBody Map<String, Integer> request) {
    Integer petId = request.get("petId");
    Integer friendId = request.get("friendId");
    Pet currentPet = petRepository.findById(petId)
            .orElseThrow(() -> new RuntimeException("当前宠物不存在"));
    Friend newFriend = new Friend(friendId);
    currentPet.getFriendsList().add(newFriend);
    petRepository.save(currentPet);
    return new ResponseEntity<>(newFriend, HttpStatus.CREATED);
}

内容的提问来源于stack exchange,提问作者craftdeer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 04:30:05