休眠 JPA 单向一对一联接 - 在插入为空外键后更新空外键



我正在尝试使用在 Spring-Boot Web 应用程序中使用 JPA Hibernate 的单向一对一映射来实现以下场景:

  1. 使用CrudRepository.save((在实体中插入记录 (实体二(,另一个实体(实体一(的外键为空
  2. 更新插入的 记录以使用CrudRepository.save((将外键设置为非空值

实体 1 如下所示:

@Entity
public class EntityOne implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "entity_one_id", updatable = false, nullable = false)
private Long id;
}

实体二如下所示:

@Entity
public class EntityTwo implements Serializable {
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "entity_one_id")
private EntityOne entityOne;
}

所以这是保存调用的样子

首次保存调用:

EntityTwo entityTwo = new EntityTwo();
entityTwoRepository.save(entityTwo);

第二次保存调用:

EntityOne entityOne = entityOneRepository.getByEntityOneId(1); // this results in a not-null value
EntityTwo entityTwo = new EntityTwo();
entityTwo.setEntityOne(entityOne);
entityTwoRepository.save(entityTwo);

在第二次调用之后,我希望外键将在实体二中设置,但事实并非如此。如果我做错了什么,或者是否有更好/其他方法可以使用 Spring-Boot JPA 实现此目的,请告诉我

你应该级联操作。

@Entity
public class EntityOne implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "entity_one_id", updatable = false, nullable = false)
private Long id;
}
@Entity
public class EntityTwo implements Serializable {
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "entity_one_id")
private EntityOne entityOne;
}

尝试;

EntityOne entityOne = new EntityOne();
EntityTwp entityTwo = new EntityTwo();
entityTow.setEntityOne(entityOne);
entityTwoRepository.save(entityTwo);

最新更新