M
M
MaxLich2019-03-12 20:04:49
Java
MaxLich, 2019-03-12 20:04:49

How to delete a related entity when unbinding from it?

Hello. It is not possible to make it so that when unbinding from a related entity, it was deleted from the database. Communication one-to-one. If I nullify the reference to the related entity or put another object there and update the main entity, then it does not delete the old related entity. If null, it does nothing at all. If the set is another entity, then another entry is created in the database in the table of the related entity. But due to the 1-1 relationship, errors occur when getting the main entity by id.
Main entity:

@Entity
@Table(name = "request", schema = "gr")
public class RequestEntity implements Serializable {

// some fields and getters and setters
    @OneToOne(mappedBy = "requestByRequestId", orphanRemoval = true, cascade = {CascadeType.ALL})
    public RejectionEntity getRejectionByRequestId() {
        return rejectionByRequestId;
    }

    public void setRejectionByRequestId(RejectionEntity rejectionByRequestId) {
        this.rejectionByRequestId = rejectionByRequestId;
    }
}

Related entity:
@Entity
@Table(name = "rejection", schema = "gr")
public class RejectionEntity implements Serializable {

// some fields and getters and setters
    @JsonIgnore
    @OneToOne
    @JoinColumn(name = "REQUEST_ID", referencedColumnName = "REQUEST_ID", nullable = false)
    public RequestEntity getRequestByRequestId() {
        return requestByRequestId;
    }

    public void setRequestByRequestId(RequestEntity requestByRequestId) {
        this.requestByRequestId = requestByRequestId;
    }
}

That is, I want that when executing some code like this:
requestEntity.setRejectionByRequestId(null);

getSession().update(requestEntity);

a record was deleted from the Rejection table with a link to the corresponding record from the Request table. Now this is not happening.
Also, if you run some code like this:
RejectionEntity rej = requestEntity.getRejectionByRequestId(); // != null
requestEntity.setRejectionByRequestId(new RejectionEntity());

getSession().update(requestEntity);

Then another record is created in the Rejection table, with a link to the record from the Request table. And the old entry referring to the same entry in the Request table is not removed from the Rejection table. Because of this, then, when getting an entity by id, an error occurs, and the entity is not returned.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question