I use JPA with Hibernate.
I have a User class and a Flag class :
class User
{
// ...
}
class Flag
{
@OneToOne(optional=false)
private User user;
}
I dont want/need a reference to the Flag object in the User class (and that’s the main point). But when I delete a User, I’d like the associated Flag (if there’s one) to be deleted too, without any foreign key constraint fails exception!
I know I could add a reference to the Flag inside the User, like :
class User
{
@OneToOne(optional=true, cascade=CascadeType.ALL, mappedBy="user")
@org.hibernate.annotations.Cascade(value=org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private Flag flag;
}
And then the Flag object would be deleted when I delete the user.
But is it possible to cascade delete the Flag without having a reference to it in the User?
If not, what if the correct way to delete such an object?
You can’t cascade the delete automatically in this case, you’ll need to implement your own delete.
When you delete a user, first run a query like: