Spring Boot:与@JoinColumn 的 ManyToOne 关系保持外键为空

Posted

技术标签:

【中文标题】Spring Boot:与@JoinColumn 的 ManyToOne 关系保持外键为空【英文标题】:Spring Boot: ManyToOne relation with @JoinColumn keeps the foreign key null 【发布时间】:2021-06-30 04:55:04 【问题描述】:

https://www.baeldung.com/jpa-joincolumn-vs-mappedby

遵循相同的方法来创建 oneToMany 和 ManyToOne 关系映射。

即使在拥有方实体中使用了@JoinColumn,根据“电子邮件实体”中的“baeldung”示例,但它将外键保持为空。

当我在父实体中使用@JoinColumn 时,即按照上面“员工”实体中的示例,它就起作用了。

但是这种关系映射行为背后的原因是什么?为什么这个示例方法不正确?

这是我的代码仓库链接:https://github.com/TamtePrathamesh/sb_mapping 在“用户”和“移动”之间,同时保持 oneToMany/ManyToOne 映射移动表而不维护外键,条目为“NULL”。 Mobile Mapping Table

【问题讨论】:

我认为您遇到的问题不是很清楚。也许您可以向我们展示您是如何映射我们的实体的,以及您遇到的确切错误? 我已附上代码仓库链接,您可以检查代码。 在 github 代码示例中,'mobile' 实体不维护 ManyToOne 关系,它总是在外键列中插入 NULL 您需要在问题中显示实体以及如何将实体 mobile 保存在数据库中。您是否更新了两个实体中的关联? mobile.user = useruser.mobiles.add(mobile) ***.com/questions/20068742/… 【参考方案1】:

在处理双向关联时,您需要更新双方的关联:

Mobile mobile = ...
User user = ...
user.mobiles.add(mobile);
mobile.user = user;

save(user);

【讨论】:

以上是关于Spring Boot:与@JoinColumn 的 ManyToOne 关系保持外键为空的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot中@OneToMany与@ManyToOne几个需要注意的问题

Spring Boot JPA 查询不为空

错误:带有 Spring 控制器的 javax.persistence.JoinColumn.foreignKey()Ljavax/persistence/ForeignKey

JoinColumn解释

@JoinColumn解释

@JoinColumn