简体   繁体   中英

Embeddable entity with @OneToOne attribute

I recently had the need to map a one-to-one entity from an embbeded entity:

@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).

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 . This causes objects C not attached to any entity A.

My solution was to duplicate the information of the relation one to one in the entity 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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