删除其他实体中@ManyToMany引用的休眠实体



我想删除食谱(使用弹簧数据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".

我的实体:

@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 {
...
}

如何删除配方实例?

您需要处理级联类型,默认情况下设置为 ALL。

例如,您可以像这样解决约束:

@ManyToMany(cascade = CascadeType.DETACH)

更多信息 : 级联类型文档

您需要从拥有实体端(即帐户)中删除。

因此,首先从帐户中的食谱列表中删除配方并保存帐户,然后删除配方本身。

正如Amer Qarabsa所指的那样,我不得不从帐户中删除食谱。

  1. 我在食谱中添加了新字段以获得双向映射

    @ManyToMany(cascade = CascadeType.MERGE, mappedBy = "favouriteRecipes")
    private Set<Account> recipeLovers = new HashSet<>(0);
    
  2. 服务类中的代码以从所有帐户中删除配方+清除配方中的恋人(此处未初始化配方和recipeId变量)

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

最新更新