java - 刷新实体A和B,当B的主键也是A的?在 JPA 和休眠中
问题描述
我有以下实体 A 和 B
@Entity
@Data
@Accessors(chain = true)
public class A {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "aId")
private long aId;
@OneToOne(mappedBy="a", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private B b;
@Entity
@Data
@Accessors(chain = true)
public class B {
@Id
@Column(name = "bId")
/**
*
* This is the same id as A.
*/
private long bId;
@OneToOne
@JoinColumn(name = "bId")
private A a;
我如何刷新实体 A 和 B
A aEntity = new A();
B bEntity = new B();
aEntity.setbEntity(bEntity);
this.entityManager.persist(A);
this.entityManager.persist(B);
this.entityManager.flush();
我正在尝试将这两个实体保存在事务中,但我遇到了 B 的 id 没有被 A 的 id 水合的问题。
解决方案
在A.b
你有一个mappedBy="a"
,这意味着它B.a
是关系的“所有者”。所以你应该设置B.a
而不是A.b
保持关系:
B bEntity = new B();
A aEntity = new A();
bEntity.setbEntity(aEntity);
this.entityManager.persist(A);
this.entityManager.persist(B);
this.entityManager.flush();
如果您需要在同一事务中继续与这些实体合作,则调用entityManager.refresh
实体将确保所有属性同步。
推荐阅读
- javascript - 单击完成时从 setInterval 停止循环
- swift - Eureka-根据 ActionSheetRow 值隐藏行
- mysql - 如果在远程运行 MySql 是 jdbc url 主机仍然是 localhost
- php - 在上传之前防止 wordpress 损害图像质量
- python - 使用 pyinstaller 编译 python 脚本后,获取应用程序无法在您的 PC 上运行
- python - 复系数多项式的 Sympy 简化
- python - 为什么实例和类调用的类方法不是一回事
- node.js - 如何从 Digital Ocean Load Balancer -> Nginx -> Node 脚本获取真实 IP 地址?
- javascript - 在 DialogFlow 内联编辑器中使用“request-promise-native”包
- angular - Angular 6 AuthGuard