我正在使用带有
例子:
这是我的现有对象:
CrudRepository
的Spring Data。我试图使用级联保存父对象和子对象,并且我让Hibernate有可能合并子实体,但是我遇到了错误a different object with the same identifier value was already associated with the session
。这可能发生在已持久化具有其他子实体(RecipeIngredients
)的两个父实体时。我尝试重写equals和hashcode,只关注id
和name
,但没有任何改变。 Recipe
对象相同,但List<RecipeIgredients>
不同。有什么解决方法吗?例子:
这是我的现有对象:
{
"id": 100,
"name": "salat",
"ingredients": [
{
"ingredient": {
"id": 100,
"name": "banana"
},
"count": 2
},
{
"ingredient": {
"id": 1,
"name": "eggs"
},
"count": 1
}
]
}
我希望将其更新为以下版本(去掉一个成分):
{
"id": 100,
"name": "salat",
"ingredients": [
{
"ingredient": {
"id": 100,
"name": "bannana"
},
"count": 2
}
]
}
父元素:
@Entity
@Data
public class Recipe {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "recipe_generator")
@SequenceGenerator(name="recipe_generator", sequenceName = "recipe_seq")
@Column(name = "id", nullable = false)
private Long id;
@NaturalId
@Column
private String name;
@OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL, orphanRemoval = true)
private List<RecipeIngredients> ingredients;
}
中下游参战者
@Entity
@Data
public class RecipeIngredients implements Serializable {
@EmbeddedId
private RecipeIngredientsId recipeIngredientsId;
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("recipeId")
private Recipe recipe;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@MapsId("ingredientId")
private Ingredient ingredient;
@Column
private Integer count;
public RecipeIngredients(Recipe recipe, Ingredient ingredient) {
this.recipe = recipe;
this.ingredient = ingredient;
this.recipeIngredientsId = new RecipeIngredientsId(recipe.getId(), ingredient.getId());
}
}
子节点
@Entity
@Data
public class Ingredient {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ingredient_generator")
@SequenceGenerator(name="ingredient_generator", sequenceName = "ingredient_seq")
@Column(name = "id", updatable = false, nullable = true)
private Long id;
@NaturalId
@Column(unique = true)
private String name;
}