[英]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".
我想删除Recipe(使用Spring数据DAO)但我得到了SQL异常:
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. 您需要处理级联类型,默认情况下设置为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. 正如Amer Qarabsa所提到的,我必须从账户中删除食谱。
I added new field in Recipe to get bidirectional mapping 我在Recipe中添加了新字段以获得双向映射
@ManyToMany(cascade = CascadeType.MERGE, mappedBy = "favouriteRecipes") private Set<Account> recipeLovers = new HashSet<>(0);
Code in service class to remove recipe from all accounts + clear lovers in recipe (recipe and recipeId variables are not initialized here) 服务类中的代码从所有帐户中删除配方+配方中的明确恋人(配方和recipeId变量未在此处初始化)
Set<Account> recipeLovers = recipe.getRecipeLovers(); recipeLovers.forEach(account -> account.getFavouriteRecipes() .removeIf(r -> r.getId() == recipeId)); recipeLovers.clear(); recipeDao.delete(recipe);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.