Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate - Can't delete child if parent has cascade set

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);
}
like image 325
Fip Avatar asked Jan 23 '26 23:01

Fip


1 Answers

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<>();
...
}
like image 59
priteshbaviskar Avatar answered Jan 26 '26 13:01

priteshbaviskar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!