I can’t seem to get cascading for entity removal working. Because of the way my Data is structured, I have to use a combination of @OnRemove(action = ...)
and normal cascading (e.g. @OneToOne(cascade = ...)
). To better illustrate the problem, here are a few entities as an example:
@Entity
class User {
@Id
String username;
}
@Entity
class Post {
@Id
@GeneratedValue
UUID id;
@ManyToOne
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "user")
User user;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "attachment")
Attachment attachment;
}
@Entity
class Attachment {
@Id
@GeneratedValue
UUID id;
String content;
}
As you can see, I have two unidirectional relationships, from the Post
to the User
and from the Post
to the Attachment
. I do not want to have a bidirectional relationship between either of them, because a User
is included in very many Post
-like entities, and an Attachment
can be used by virtually anything.
You can also see the cascading I am trying to implement. It should work like this:
- I delete a
User
. - All
Post
s of theUser
are deleted, specified by@OnDelete(action = OnDeleteAction.CASCADE)
- The
Attachment
of everyPost
is in turn deleted, specified bycascade = CascadeType.ALL
in the relation Annotation.
However, this does not work as anticipated, as the user User
and associated Post
entities are deleted, but the Attachments
are not. This is problematic, since I then have orphaned Attachment
s in my database, which I would have to remove manually. I have also tried specifying orphanRemoval = true
, but that doesn’t do anything either.
I have a hunch on why this does not work as expected, but please correct me if I am being wrong:
As far as I know is the deletion of entities with @OnDelete
handled on the database itself, specified by the foreign key constraint (something like constraint ... foreign key (user) references user (username) on delete cascade
). However, the cascading using cascade = CascadeType.ALL
is managed by Hibernate itself and is not done by the database.
So what I think what happens is that Hibernate tells the database to delete the User
. The database then goes on deleting the User
, following the foreign key constraint, also deleting the Post
s. But Hibernate does not know that these Post
s were deleted, so no further cascading, which would be handled by Hibernate, happens.
So, my questions are the following:
How could I make this work as expected?
Is there a way of using @OnRemove
which is not done over the database?
Or the other way round, can I cascade the rest also over foreign key constraints?
I am using Spring Boot 3.1 with Hibernate 6.2.