gpt4 book ai didi

java - Hibernate OrphanRemoval 仅从关系表中删除数据

转载 作者:太空宇宙 更新时间:2023-11-04 14:19:40 24 4
gpt4 key购买 nike

我有一个 RECIPE 表,它与 INGREDIENT 表具有 OneToMany 关系,因为单个配方可以包含多种成分。问题是,如果用户删除一个成分(前端将所有字段(ingredient_idingredient)设置为 NULL),则包含两个表的关系的行RECIPE_INGREDIENT 已删除,但 Ingredient 表中的行仍然存在。我们不能告诉 Hibernate 也删除这些行吗?

Oracle表

create table recipe(id number primary key,
name varchar2(25) unique);

create table ingredient(ingredient_id number(4) primary key,
ingredient varchar2(40));

create table recipe_ingredient(recipe_id number(4),
ingredient_id number(4),
constraint recipe_fk foreign key(recipe_id)
references recipe(recipe_id),
constraint ingredient_fk foreign
key(ingredient_id) references
ingredient(ingredient_id));

POJO的成分和配方

@Entity
@Table(name = "ingredient", uniqueConstraints={
@UniqueConstraint(columnNames="INGREDIENT_ID")
})
public class Ingredient implements Serializable {
@Id
@Column(name = "INGREDIENT_ID", unique=true, nullable=false)
@SequenceGenerator(name="seq_ingredient", sequenceName="seq_ingredient")
@GeneratedValue(strategy=GenerationType.AUTO, generator="seq_ingredient")
private Integer ingredientId;

@Column(name = "INGREDIENT")
private String ingredient;

/*@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="RECIPE_ID")
private Recipe recipe;*/

//getter and setters



@Entity
@Table(name = "recipe")
public class Recipe implements Serializable {
@Id
@Column(name = "id")
private Integer id;

@Column(name = "name")
private String name;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinTable(name = "recipe_ingredient", joinColumns = { @JoinColumn(name = "recipe_id") }, inverseJoinColumns = { @JoinColumn(name = "ingredient_id") })
private List<Ingredient> ingredients;

//getters and setter
}

DAO 代码

public class RecipeDaoImpl implements RecipeDao {
public void addRecipe(Recipe recipe) {
getSession().saveOrUpdate(recipe);
}
}

日志显示 INGREDIENT 表中的行仍然存在,而 Hibernate 只是从“RECIPE_INGREDIENT”表中删除行。

请参阅以下内容,ingredient_idnull 已被删除。在这两种情况下,它都会将 ingredient.recipe_id 更新为 NULL。

Received following from frontend:
RecipeController - Recipe[recipeId=126,name=Sandwich,ingredients=[Ingredient[ingredientId=270,ingredient=Salt],[ingredientId=<null>,quantity=<null>]]]

Hibernate: update RECIPE set NAME=? where RECIPE_ID=?
Hibernate: update ingredient set INGREDIENT=? where INGREDIENT_ID=?
Hibernate: delete from recipe_ingredient where recipe_id=?
Hibernate: insert into recipe_ingredient (recipe_id, ingredient_id) values (?, ?)

所以数据库表有,

INDREDIENT
INGREDIENT_ID INGREDIENT
271 Salt
272 Sugar

RECIPE_INDGREDIENT
RECIPE_ID INDREDIENT_ID
126 271

最佳答案

您是否在 Receipe 和 Indgredient 类中正确实现了 equals() 和 hashcode() 方法?如果不是,则可能是 indgrient 表中的行未被删除的原因。阅读 this文章了解更多详细信息。

关于java - Hibernate OrphanRemoval 仅从关系表中删除数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27339620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com