我正在将Spring Data JPA与JpaRepository一起使用,但找不到为什么我的实体被分离并且我无法使用子实体保存的答案。
我想保存配方,但首先我需要将成分保存在另一项服务中。配方和成分通过RecipeIngredients对象建立了多对多关系。
@Transactional
public RecipeDto updateRecipe(UserPrincipal userPrincipal, String recipeName, RecipeDto recipeDto) {
Recipe recipeToEdit = recipeRepository.findByName(recipeName).orElseThrow(EntityNotFoundException::new);
recipeToEdit.setIngredients(recipeIngredientsService.refillRecipeIngredientsList(recipeDto.getIngredients(), recipeToEdit));
}
@Entity
public class RecipeIngredients {
@EmbeddedId
private RecipeIngredientsId recipeIngredientsId;
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("recipeId")
@ToString.Exclude
private Recipe recipe;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE})
@MapsId("ingredientId")
@ToString.Exclude
private Ingredient ingredient;
}
@Entity
@Getter
@Setter
public class Ingredient {
@Id
@Column(name = "id", updatable = false)
private Long id;
@OneToMany(mappedBy = "ingredient", cascade = CascadeType.ALL, orphanRemoval = true)
@ToString.Exclude
private List<RecipeIngredients> recipeIngredients;
public void addRecipeIngredient(RecipeIngredients recipeIngredient) {
if(recipeIngredients == null) {
recipeIngredients = new ArrayList<>();
}
recipeIngredients.add(recipeIngredient);
recipeIngredient.setIngredient(this);
}
}
在我要保存 Ingredient 实体之前,我要检查是否存在,因此我从外部服务中将其拉出,然后将其映射到DTO对象。如果没有成分,我要保存并获取他的对象,该对象将与 RecipeIngredients 的子级关联,并且此对象与 Recipe 相关,因此当我正在保存食谱,它应该为我保存 RecipeIngredient 。
public void refillRecipeIngredientsList(List<RecipeIngredientsDto> recipeIngredientsDtos, Recipe recipe) {
removeOldIngredientsIfExist(recipe);
if (recipeIngredientsDtos != null) {
for (RecipeIngredientsDto recipeIngredientsDto : recipeIngredientsDtos) {
IngredientDto ingredient = pullSavedIngredient(recipeIngredientsDto);
RecipeIngredients recipeIngredient = this.recipeIngredientsDtoToEntityMapper.recipeIngredientsToEntity(recipeIngredientsDto, recipe, ingredientDto);
recipe.addIngredient(recipeIngredient);
ingredient.addRecipeIngredient(recipeIngredient);
}
}
}
但是我以各种方式收到了org.hibernate.PersistentObjectException: detached entity passed to persist: com.app.todaysdinner.entity.ingredient.Ingredient
。有人知道答案如何重新附加成分实体吗?
[编辑]
我发现,当我想通过Recipe
上的RecipeIngredients
级联进行更新时,还要级联到Ingredients上,这意味着即使仅允许cascade = {CascadeType.MERGE}
,它也会调用PERSISTANCE方法。但是我找不到答案,为什么在一个@Transaction
对象中被分离。