【发布时间】:2020-08-19 17:57:02
【问题描述】:
我正在使用带有 CrudRepository 的 Spring Data。我正在尝试将具有 Cascade 的父级保存给子级,并且我正在为 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;
}
【问题讨论】:
标签: hibernate jpa spring-data-jpa hibernate-mapping