AssylkhanAz
AssylkhanAz

Reputation: 1

OneToOne delete data

how can I delete data in one table and not affect data from 2 tables? for example, I want to delete resume_id 5 -> user_id 12. If I delete resume_id 5, then user_id 12 is also deleted. how to fix it?

@JsonBackReference(value="resume")
@OneToOne(mappedBy = "userinfo", cascade = CascadeType.REMOVE)
private EntityResume resume;

@JsonManagedReference(value = "resume")
@OneToOne(cascade = CascadeType.REMOVE)
@JoinColumn(name = "user_id", unique = true)
private EntityUserInfo userinfo;

Upvotes: 0

Views: 48

Answers (2)

You used CascadeType.REMOVE on both ends of the bidirectional link. Accordingly, when both parent and child entities are deleted, the entity on the other end of the link will also be deleted. Get rid of CascadeType.REMOVE on the child entity and use the orphanRemoval property

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

Upvotes: 1

The problem is that you are configuring @JoinTable with (cascade = CascadeType.ALL) .

That means that all operations will be propagated to any child of the entity that gets deleted. You can either remove the cascade property so that no operation is cascaded or you can configure it for specified operations.

See CascadeTypes detailed here: https://www.baeldung.com/jpa-cascade-types

Upvotes: 1

Related Questions