Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cascade delete a @OneToOne member

@Entity public class Organization {

    @OneToOne(fetch = FetchType.EAGER)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @Cascade(value = DELETE_ORPHAN)
    private Days days;

}

I have the following entity definition and it generates a SQL to do a cascade delete on the @OneToOne entry when the parent object gets deleted. But it's not removing the "days" entry while deleting an Organization.

This happens with h2, mysql databases, what could be the problem here.

like image 433
Sam Avatar asked Nov 11 '10 04:11

Sam


People also ask

What is on delete cascade and on delete restrict?

The ON DELETE CASCADE and ON DELETE RESTRICT are the foreign key properties and you set them when you create the relationship between two tables.

Is Cascade delete a good idea?

Why sql server cascade delete is bad? sql server cascade delete should not cause an unexpected loss of data. If a delete requires related records to be deleted, and the user needs to know that those records are going to go away, then cascading deletes should not be used.


1 Answers

Well, I guess you should add a

@Cascade(value = {DELETE, DELETE_ORPHAN})

Note that in JPA 2.0 you don't have to use the hibernate-sepcific @Cascade annotation - @*ToMany has an option to delete orphans.

Update: when using queries cascades are not handled. You have to handle them manually. This is expected and documented behaviour.

like image 146
Bozho Avatar answered Oct 25 '22 00:10

Bozho