首页 > 解决方案 > 具有@OneToOne 属性的可嵌入实体

问题描述

我最近需要从一个嵌入实体映射一个一对一的实体:

@Entity
public class A {
  
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Embedded
  private B b;

  //getters and setters
}

@Embeddable
public class B {
  @OneToOne(mappedBy="a", cascade = CascadeType.ALL, orphanRemoval = true)
  private C c;

  //getters and setters
}

@Entity
public class C {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @OneToOne
  @JoinColumn(name="a_id")
  private A a;

  //other fields, getters and setters
}

当我们创建、更新实体 c 的信息并删除 a(并因此删除 c)时,此映射正常工作。

问题是当我们尝试通过更新删除 C时,真正发生的是休眠更新实体 C 并将 a_id 字段设置为 null。这会导致对象 C 未附加到任何实体 A。

标签: javahibernatejpaone-to-oneembeddable

解决方案


我的解决方案是在实体 A 中一对一地复制关系信息

@Entity
public class A {
  
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Embedded
  private B b;

  @OneToOne(mappedBy="a", cascade = CascadeType.ALL, orphanRemoval = true)
  private C c;
  
  public void setB(final Optional<B> b) {
    b.ifPresentOrElse(newB -> {
      newB.getC().ifPresent(c -> {
        c.setA(this);
        this.b = b;
      }, () -> {
        this.c = null;
        this.b = null;
      });
  }

  // other getters and setters
}

有没有办法不复制A中实体C的信息并保持正确的行为?


推荐阅读