简体   繁体   English

Hibernate:在更新父实体的同时更新子实体?

[英]Hibernate: Updating child entities while updating parent entity?

I have the following entities with a proper mapping and can create records properly by child entities.我有以下具有适当映射的实体,并且可以通过子实体正确创建记录。 For example, when creating a Recipe, I can add Ingredients to this recipe and just save this recipe via its entity.例如,当创建一个食谱时,我可以将成分添加到这个食谱中,然后通过它的实体保存这个食谱。 Then recipe is created with its ingredients properly.然后使用其成分正确创建食谱。

Now I need to update the Recipe and at this stage I am not sure what is the most proper way in Hibernate to update child record.现在我需要更新食谱,在这个阶段我不确定 Hibernate 中更新子记录的最合适方法是什么。 I set the Recipe fields by request, but what should I do if the original Recipe has 3 ingredients (let's say IngA, IngB, IngC) and the updated ingredient has same and different ingredients (let's sat IngA, IngX, IngY).我根据要求设置了配方字段,但是如果原始配方有 3 种成分(假设是 IngA、IngB、IngC)并且更新后的成分具有相同和不同的成分(假设是 IngA、IngX、IngY),我该怎么办?

At this stage, should I remove all the ingredients belonging to the Recipe and then add all the ingredients coming from update request?在此阶段,我是否应该删除属于 Recipe 的所有成分,然后添加来自更新请求的所有成分?

Or how should I treat the child data for update?或者我应该如何对待子数据进行更新?

Here is my update method which needs to be completed:这是我需要完成的更新方法:

public void update(RecipeRequest request) {
    final Recipe recipe = recipeRepository.findById(request.getId())
            .orElseThrow(() -> new NoSuchElementFoundException(NOT_FOUND_RECIPE));
    recipe.setTitle(capitalizeFully(request.getTitle()));

    request.getRecipeIngredients().stream()
            .forEach(recipeIngredient -> {
                // get each of the requested ingredients
                final Ingredient ingredient = ingredientRepository.findById(recipeIngredient.getIngredientId())
                        .orElseThrow(() -> new NoSuchElementFoundException(NOT_FOUND_INGREDIENT));
                // then add to the RecipeIngredient (bridge table)
                recipe.addRecipeIngredient(new RecipeIngredient(recipe, ingredient));
            });
    recipeRepository.save(recipe);
}

Just clear the collection after loading the Recipe and then it should work fine.只需在加载Recipe后清除集合,然后它就可以正常工作。 Hibernate will do the deletes for you automatically. Hibernate 会自动帮你删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM