首页 > 解决方案 > 刷新实体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 水合的问题。

标签: javahibernatejpaorm

解决方案


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实体将确保所有属性同步。


推荐阅读