简体   繁体   English

具有@OneToOne 属性的可嵌入实体

[英]Embeddable entity with @OneToOne attribute

I recently had the need to map a one-to-one entity from an embbeded entity:我最近需要 map 来自嵌入式实体的一对一实体:

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

This mapping works correctly when we create, update the information for entity c and delete a (and consequently deletes c).当我们创建、更新实体 c 的信息并删除 a(并因此删除 c)时,此映射正常工作。

The problem is when we try to remove C through an update , what really happens is that hibernate updates entity C and sets the a_id field to null .问题是当我们尝试通过更新删除 C时,真正发生的是 hibernate更新实体 C 并将 a_id 字段设置为 null This causes objects C not attached to any entity A.这导致对象 C 未附加到任何实体 A。

My solution was to duplicate the information of the relation one to one in the entity A我的解决方案是在实体 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
}

Is there any way to not duplicate the information of entity C in A and maintain the correct behavior?有没有办法不重复 A 中实体 C 的信息并保持正确的行为?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM