Search code examples
javahibernatejpahibernate-mappingcascade

Hibernate: delete the parent/owner while keeping the child in one-to-one relationship


I have two Entity Classes: UserConfirmation and User, they are one-to-one relationship using the following annotated code:

the Parent/Owner Entity (UserConfirmation):

@OneToOne(mappedBy = "userConfirmation", cascade = CascadeType.ALL)
    @JsonManagedReference
    private User user;

the Child Entity (User):

@OneToOne
@JoinColumn(name = "user_confirm_id")
@JsonBackReference
private UserConfirmation userConfirmation;

With the current Cascade.ALL, when I delete the UserConfirmation, its associated User also gets deleted, which I do not want. I would like to keep the User after deleting the UserConfirmation.

I've tried the following:

  1. Set the user to null before deleting UserConfirmation: userConfirmation.setUser(null); but this gives a NullPointerException

  2. tried Cascade.REMOVE and almost everything on Cascade, but none works.

Your help is appreciated as always :)


Solution

  • You cannot delete a parent without removing all child-side parent Foreign Key associations.

    In your example you say that the UserConfirmation is the parent and the User is the child, but this is not correct.

    The parent side is the one that's independent of the other side existance. In your case the User should be the parent and the UserConfirmation should be the child side.

    So, the User has:

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
    private UserConfirmation userConfirmation;
    

    It's the parent that cascades entity state transitions to children.

    And the UserConfirmation is the child, yet it's the owner-side:

    @OneToOne
    @JoinColumn(name = "user_id")
    @JsonBackReference
    private User user;
    

    Now you can delete a UserConfirmation while leaving the User untouched.