【问题标题】:Embeddable entity with @OneToOne attribute具有@OneToOne 属性的可嵌入实体
【发布时间】:2021-01-27 17:25:13
【问题描述】:

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

@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。

【问题讨论】:

    标签: java hibernate jpa one-to-one embeddable


    【解决方案1】:

    我的解决方案是在实体 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的信息,保持正确的行为?

    【讨论】:

      猜你喜欢
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多