【问题标题】:Why is Hibernate not updating the Foreign key column for OneToOne relation?为什么 Hibernate 不更新 OneToOne 关系的外键列?
【发布时间】:2026-02-22 03:25:01
【问题描述】:
@Entity
@Table(name = "t1")
public class Object1 {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "f_id")
  private Long id;

  @OneToOne(cascade = {CascadeType.ALL},mappedBy = "object1")
  private Object2 object2;

}

@Entity
@Table(name = "t2")
public class Object2 {

  @Id
  @Column(name = "f_id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @OneToOne
  @JoinColumn(referencedColumnName = "f_id",name = "f_integration_id",insertable = false, updatable = false)
  private Object1 object1;
}

t1 有一列 f_id 是它的主键。表 t2 有一个列 f_integration_id 引用表 t1 中的 f_id 列。

现在,当我尝试保存 Object1 时,它会在 t1t2 两个表中创建 2 行。但是表 t2 中的外键列仍然是 NULL 。有人可以告诉为什么会这样吗?虽然它对 OneToMany 关系很有吸引力。

【问题讨论】:

  • 你应该提供实体持久化代码。
  • 嘿@alexvaluiskyi 没有太多的持久性代码。我正在扩展 JPARepository 而不是实体管理器。所以持久化代码就是repository.saveAndFlush(object1)
  • 我的意思是您创建实体并将其保存到数据库的服务方法。您必须分配两个侧面对象关系
  • 如果您签入我提供的 sn-p,我确实在 Object1 和 Object2 中定义了双向映射。
  • 你应该在持久化之前设置双方关系:object1.setObject2(object2); object2.setObject1(object1);

标签: java hibernate jpa hibernate-mapping one-to-one


【解决方案1】:

我认为问题出在下面一行。您的设置可更新和可插入为 false。所以它不会插入或更新。你可以参考这个Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation

@JoinColumn(referencedColumnName = "f_id",name = "f_integration_id",insertable = false, updatable = false)

【讨论】: