简体   繁体   中英

Delete hibernate entity which is referenced by @ManyToMany in other entity

I want to delete Recipe (using spring data DAO) but I got SQL exception: org.postgresql.util.PSQLException: ERROR: update or delete on table "recipe" violates foreign key constraint "fkacys689tmdmfggtf4thdoc83k" on table "favourite_recipes" Detail: Key (id)=(76823) is still referenced from table "favourite_recipes".

My entities:

@Entity
public class Account {

  @ManyToMany(fetch = FetchType.LAZY)
  @JoinTable(name = "favourite_recipes",
    joinColumns = @JoinColumn(name = "account_id"),
    inverseJoinColumns = @JoinColumn(name = "recipe_id"))
  private Set<Recipe> favouriteRecipes = new HashSet<>(0);

  ...
}


@Entity
public class Recipe {
  ...
}

How to remove recipe instance?

You need to handle the cascade type, by default is set to ALL.

For example you can work around the contraints like this:

@ManyToMany(cascade = CascadeType.DETACH)

more info : cascade type docs

in you need to delete from the owning entity side which is the Account.

So first remove the recipe from recipe list in Account and save the account, then remove the recipe itself.

As Amer Qarabsa metioned I had to remove recipe from Account.

  1. I added new field in Recipe to get bidirectional mapping

     @ManyToMany(cascade = CascadeType.MERGE, mappedBy = "favouriteRecipes") private Set<Account> recipeLovers = new HashSet<>(0); 
  2. Code in service class to remove recipe from all accounts + clear lovers in recipe (recipe and recipeId variables are not initialized here)

     Set<Account> recipeLovers = recipe.getRecipeLovers(); recipeLovers.forEach(account -> account.getFavouriteRecipes() .removeIf(r -> r.getId() == recipeId)); recipeLovers.clear(); recipeDao.delete(recipe); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM