【发布时间】:2020-10-10 18:47:10
【问题描述】:
我正在尝试在 Spring-Boot Web 应用程序中使用 JPA Hibernate 使用单向 OneToOne 映射来实现以下场景:
- 使用 CrudRepository.save() 在实体中插入记录 (EntityTwo) 与另一个实体 (EntityOne) 的外键为 null
- 更新插入的 记录使用 CrudRepository.save() 将外键设置为非空值
实体一看起来像这样:
@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);
第二次调用后,我希望在 EntityTwo 中设置外键,但事实并非如此。如果我做错了什么,或者是否有更好的/其他方法可以使用 Spring-Boot JPA 实现这一点,请告诉我
【问题讨论】:
标签: java spring-boot hibernate jpa