gpt4 book ai didi

java - 在 Google App Engine 上使用 JDO 更新 "nested"对象

转载 作者:行者123 更新时间:2023-11-30 07:38:47 24 4
gpt4 key购买 nike

我无法找到使用 Google App Engine 更新“嵌套”数据的正确方法和 JDO。我有一个 RecipeJDO和一个 IngredientJDO .

我希望能够用新的配料列表完全替换给定食谱实例中的配料。然后,当该食谱被(重新)保留时,任何先前附加的成分都将从数据存储中完全删除,新的成分将被保留并与该食谱相关联。

类似于:

  // retrieve from GAE datastore
RecipeJDO recipe = getRecipeById();

// fetch new ingredients from the user
List<IngredientJDO> newIngredients = getNewIngredients();
recipe.setIngredients(newIngredients);

// update the recipe w/ new ingredients
saveUpdatedRecipe(recipe);

当我直接更新(分离)从数据存储返回的配方对象时,这工作正常。但是,如果我复制 RecipeJDO,然后进行上述更新,它最终会添加新成分,然后当从数据存储中重新获取配方时,这些新成分会与旧成分一起返回。 (为什么要费心复制?我在前端使用 GWT,所以我将 JDO 对象复制到 DTO,用户在前端编辑它们,然后将它们发送到后端以更新数据存储。)

为什么我手动创建的对象(设置所有字段,包括 id)与操作 PersistenceManager 返回的实例得到不同的结果?明显地JDO 的字节码增强以某种方式参与其中。

我是否最好在坚持更新之前明确删除旧成分食谱?

(附带问题 - 有没有其他人对 ORM 感到沮丧并希望我们可以回到普通的旧 RDBMS?:-)

最佳答案

简答。将 RecipeJDO.setIngredients() 更改为:

public void setIngredients(List<IngredientJDO> ingredients) {
this.ingredients.clear();
this.ingredients.addAll(ingredients);
}

当您获取 RecipeJDO 时,ingredients 列表不是真正的 ArrayList,它是处理所包含元素持久性的动态代理。您不应该更换它。

当持久化管理器打开时,你可以遍历ingredients列表,添加项目或移除项目,当持久化管理器关闭(或提交事务,如果您正在进行交易)。以下是您如何在没有事务的情况下进行更新:

public void updateRecipe(String id, List<IngredientDTO> newIngredients) {
List<IngredientJDO> ingredients = convertIngredientDtosToJdos(newIngredients);
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
RecipeJDO recipe = pm.getObjectById(RecipeJDO.class, id);
recipe.setIngredients(ingredients);
} finally {
pm.close();
}
}

如果您从不修改IngredientJDO 对象(仅替换和读取它们),您可能希望将它们设为Serializable 对象而不是JDO 对象。如果这样做,您可以在 GWT RPC 代码中重用 Ingredient 类。

顺便说一句,即使 Recipe 不是 JDO 对象,您也需要在 setIngredients() 方法中复制一份,否则有人可以这样做:

List<IngredientJDO> ingredients = new ArrayList<IngredientJDO>;
// add items to ingredients
recipe.setIngredients(ingredients);
ingredients.clear(); // Woops! Modifies Recipe!

关于java - 在 Google App Engine 上使用 JDO 更新 "nested"对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1482570/

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