I try to delete an entity which is a child of another entity (one-to-many).
The problem is:
If the parent has set a cascade type, I am not able to delete a child directly. The delete command is ignored (using JpaRepository). Only if I remove the cascade setting I am able to delete child.
Is there a way to do this without a native SQL statement?
Parent Entity:
@Entity
public class ExplorerItem {
...
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "explorerItem")
private Set<UserACL> userAcls = new HashSet<>();
...
}
Child Entity:
@Entity
public class UserACL {
...
@ManyToOne
private ExplorerItem explorerItem;
...
}
I'm using JpaRepositories created by Spring Boot:
public interface UserACLRepository extends JpaRepository<UserACL, Long> {
void deleteByUser(User user);
}
You can set orphanRemoval="true" in your @OneToMany annotation. Setting orphanRemoval to true automatically removes disconnected references of entities. On the other hand, if we specify only CascadeType.Remove, no action is taken as it will only disconnect from the association, which is not equivalent of deleting an object.
Eg.
@Entity
public class ExplorerItem {
...
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval="true", mappedBy = "explorerItem")
private Set<UserACL> userAcls = new HashSet<>();
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With