Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

java - 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.

question from:https://stackoverflow.com/questions/65924228/embeddable-entity-with-onetoone-attribute

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...