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
297 views
in Technique[技术] by (71.8m points)

java - JPA orphan removal does not work for OneToOne relations

Does anyone have a workaround for this issue: https://hibernate.atlassian.net/browse/HHH-9663?

I am also facing a similar issue. When I created one-sided (no reverse reference) one to one relationship between two entities and set the orphan removal attribute to true, the referenced object is still in the database after setting the reference to null.

Here is the sample domain model:

@Entity
public class Parent {
  ...
  @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  @JoinColumn(name = "child_id")
  private Child child;
  ...
}

@Entity
public class Child {
  ...
  @Lob
   private byte[] data;
  ...
}

I am currently working around this by manually deleting orphans.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Cascading only makes sense for entity state transitions that propagate from a Parent to a Child. In your case, the Parent was actually the child of this association (having the FK).

Try with this mapping instead:

@Entity
public class Parent {
  ...
  @OneToOne(
      fetch = FetchType.LAZY, 
      cascade = CascadeType.ALL, 
      orphanRemoval = true, 
      mappedBy = "parent"
  )
  private Child child;
  ...
}

@Entity
public class Child {

    @OneToOne
    @JoinColumn(name = "parent_id")
    private Parent parent;

    ...
    @Lob
    private byte[] data;
    ...
}

And to cascade the orphan removal, you now need to:

Parent parent = ...;
parent.getChild().setParent(null);
parent.setChild(null);

Or even better, confgiure the setChild method in the Parent entity class to set both associations:

public void setChild(Child child) {
    if (child == null) {
        if (this.child != null) {
            this.child.setParent(null);
        }
    }
    else {
        child.setParent(this);
    }
    this.child = child;
}

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

...