2
votes

I'm trying to delete a parent/child self-join entity but unable to do so here is my mapping

@Entity
public class FolderNode  {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "hibernate_sequence")
    @SequenceGenerator(name = "hibernate_sequence", sequenceName = "hibernate_sequence")
    @Column(name="folder_id")
    private long folderId;


    @ManyToOne
    @Cascade(CascadeType.DELETE)
    @JoinColumn(name="parent_id")
    @OnDelete(action = org.hibernate.annotations.OnDeleteAction.CASCADE)
    private FolderNode parent;

}
2

2 Answers

2
votes

For correct parent/child relation modeling you should have modeled the one to many part of relation please find an example:

    @ManyToOne(cascade={CascadeType.ALL})
    @JoinColumn(name="parent_id")
    private Menu parent;
    @OneToMany(mappedBy="parent",orphanRemoval=true)
    private List<Menu> children = new ArrayList<Menu>();

This is an unidirectional link so the owner of the relation would be the parent side of the relation. Now when you issue a EM.delete(parent) or session.delete(parent) the delete will be cascaded by the chain and children will be deleted too ( normally called orphans, by default hibernate will not issue a delete statement on orphans ) so that's why orphanRemoval = true is configured.

0
votes

Though bit old to answer, but today i faced same issue, but on deleting child, parent is also getting deleted.

Do not use cascade={CascadeType.ALL} on Parent if you do wish to cascade CRUD operations from child to parent.

@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="parent_id")
private Menu parent;

@OneToMany(mappedBy="parent",orphanRemoval=true)
private List<Menu> children = new ArrayList<Menu>();

If you delete children, it also deletes the parent: you can remove cascade operations from parent.

So we can change as per below,

@ManyToOne
@JoinColumn(name="parent_id")
private Menu parent;

@OneToMany(mappedBy="parent",orphanRemoval=true)
private List<Menu> children = new ArrayList<Menu>();