java - Get Hibernate to delete association before entity -


the scenario this. have 2 entities, user , post twitter-like application. consider following

  1. user alice creates post.
  2. user bob favorites aforementioned post.
  3. 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;

  1. fetch of users have favorited post, , clear of them 1 one.
  2. 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 posts it's associated being removed.

this can solved moving ownership of user - posts relationships away user, example, follows:

  • user <- post: never need posts created user @ once (without filtering or pagination). therefore makes no sense map relationship user post, unidirectional relationship post user enough.

  • user <- favoritepost -> post: moving "favorite post" relationship own entity allows have own lifecycle. favoritepost can silently disappear when associated post removed, , won't create inconsistency @ application level.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -