JPA一对多关系“父键不能为空”的问题

问题描述 投票:0回答:1

JPA一对多关系“父键不能为空”的问题

父母 - 登记处

@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
@JoinColumn(name = "registry_id", nullable = false , insertable = true)
@PrivateOwned
public List<ContactData> getContactDataList() {
    return contactDataList;
}

child - ContactData

    @Column(name = "registry_id", length = 20)
public BigInteger getRegistryId() {
    return registryId;
}
public void setRegistryId(BigInteger registryId) {
    this.registryId = registryId;
}

子save中的错误会抛出父id不能为null

无法改变数据库端

jpa hibernate-mapping
1个回答
0
投票

问题父键不能为空,因为您正在保存没有父/主表引用的子/依赖表数据。

解:

  1. 获取父参考。您必须从Registry表加载父条目。如果不存在则创建注册表项。
  2. 创建子引用(ContactData)对象
  3. 将父引用注册表添加到子ContactData条目中。这里不仅父id添加到子,还添加父对象引用。
  4. 保存子对象

希望这能解决你的问题。

谢谢 :)

© www.soinside.com 2019 - 2024. All rights reserved.