我在开发工作中遇到了一些非常令人费解的事情。
removePreviousFoodMenuItems(oldRefList);
shFood.setNewFoodMenuItems(newRefList);
em.merge(shFood);
em.flush(); //Error occurs
如果我在合并之前调用 removePreviousFoodMenuItems,我将在运行时收到“无法合并已被删除的实体”异常。但是,这不应该发生,因为我已将 shFood 设置为引用一组新的食物菜单项 (newRefList)。那么为什么merge 还在尝试合并已经被移除的oldRefList 元素呢?如果我将 removePreviousFoodMenuItems 放在 flush 语句之后,则不会出现此问题。
shFood.setNewFoodMenuItems(newRefList);
em.merge(shFood);
em.flush(); //Error does not occur
removePreviousFoodMenuItems(oldRefList);
下面是 removePreviousFoodMenuItems 的代码
public void removePreviousFoodMenuItems(ArrayList<FoodMenuItem> oldRefList){
for (Object f : oldRefList) {
FoodMenuItem foodMenuItem = (FoodMenuItem) f;
foodMenuItem.setStakeholderFood(null);
foodMenuItem.setPhotoEntity(null);
em.remove(foodMenuItem);
//em.flush();
}//end for
}//end removePreviousFoodMenuItems
非常感谢对此的一些建议!
更新:如何创建 newRefList:
StakeholderFood stakeholder = em.find(StakeholderFood.class, stakeholderID);
ArrayList<FoodMenuItem> newRefList = new ArrayList<FoodMenuItem>();
for (Object o : menuItem) {
FoodMenuItem fmi = (FoodMenuItem) o;
FoodMenuItem newFmi = new FoodMenuItem();
String previousName = fmi.getItemName();
newFmi.setItemName(previousName);
newFmi.setItemPrice(fmi.getItemPrice());
newFmi.setPhotoEntity(fmi.getPhotoEntity());
//Upload the photos for each item attached to menuItem
Photo photo = fmi.getPhotoEntity();
if(photo!=null){
photo.setFoodmenuItem(newFmi); //set new relationship, break off with old
em.merge(photo); //This will merge newFmi as well Fix this tomorrow
em.flush(); //update the links immediately
}
if (photo != null && fmi.getContainsImage() == Boolean.FALSE) {
uploadFoodMenuItemImages(photo);
newFmi.setPhotoEntity(photo);
newFmi.setContainsImage(Boolean.TRUE);
newFmi.setRenderedImage(Boolean.FALSE);
newFmi.setRenderedImageAltText(Boolean.FALSE);
}//end photo
else {
newFmi.setRenderedImageAltText(Boolean.TRUE);
}
newFmi.setStakeholderFood(stakeholder);
newRefList.add(newFmi);
}//end for