java - Get Hibernate to delete association before entity -
the scenario this. have 2 entities, user , post twitter-like application. consider following
- user alice creates post.
- user bob favorites aforementioned post.
- user alice tries delete post.
when user alice tries delete post, error hibernate;
error: update or delete on table "posts" violates foreign key constraint "fk_jof9iwt9m3lfjxix5ejri4iv9" on table "favorite_posts" detail: key (id)=(16) still referenced table "favorite_posts".
code entities;
@table(name = "users") public class user { ... @onetomany(cascade = cascadetype.all, orphanremoval = true) private list<post> posts = new arraylist<post>(); @onetomany(cascade = cascadetype.all) @jointable(name = "favorite_posts") private set<post> favoriteposts = new hashset<post>(); ... } @table(name = "posts") public class post { ... @manytoone private user user; ... }
my alternatives see them;
- fetch of users have favorited post, , clear of them 1 one.
- make association bidirectional , clear of favorites before deletion.
how can hibernate delete association (= corresponding row in favorite_posts) before trying delete entity?
i'd solve problem @ database level using on delete cascade
on foreign key. it's simpliest solution, , doesn't bring complexity application layer.
however, approach doesn't play domain model, because model treats user
- post
relationships (both post
, favoriteposts
) parts of user
. therefore, you'll constraint violation if try save user
while 1 of post
s it's associated being removed.
this can solved moving ownership of user
- post
s relationships away user
, example, follows:
user
<-post
: never needpost
s createduser
@ once (without filtering or pagination). therefore makes no sense map relationshipuser
post
, unidirectional relationshippost
user
enough.user
<-favoritepost
->post
: moving "favorite post" relationship own entity allows have own lifecycle.favoritepost
can silently disappear when associatedpost
removed, , won't create inconsistency @ application level.
Comments
Post a Comment