pike
pike

Reputation: 711

using JPA CRUD to cascade delete parent explicitly without using annotation

Right now, if I want to delete a Parent entry from database, I would use cascade annotation in the Parent class, so that a deletion of Parent would also delete any children tied to it. Like this:

@Entity
public class Parent implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
    private Set<Child> children;
}

@Entity
public class Child implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    @ManyToOne
    @JoinColumn
    private Parent parent;  
}

The actual deletion would be like this:

this.parentRepository.delete(parentID);

However, if I want to explicitly choose whether to cascade delete or to simple delete, how would I do that?

I don't think I can choose to turn off the cascade annotation in code manually, so is there a way to cascade delete without using annotation?

Upvotes: 2

Views: 835

Answers (1)

Serhii
Serhii

Reputation: 7543

You should not delete parent if child has relation on parent. It's not good way. In db child should not have notNull restriction on parent

But you really want control cascade deletion, I would recommend use @EntityListeners:

@EntityListeners({ParentJpaCallbacksListener.class})
@Entity
public class Parent implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    @OneToMany(mappedBy = "parent")
    private Set<Child> children;
}

where

@Component
public class ParentJpaCallbacksListener {
    @Autoware ChildRepository childRepository;

    @PreRemove
    // or @PostRemove
    void preRemove(Parent parent) {
        // your cascade deletion logic 
        // for example use childRepository to delete some children
    }

}

In this way you should not have cascade = CascadeType.REMOVE.

Upvotes: 1

Related Questions