java—在一个餐厅项目中,我有一个异常:org.hibernate.persistentobjectexception:传递给persist的分离实体

zazmityj  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(270)

我有一个食物表和菜单表,每个菜单都可以有普通的食物。当我想保存或保留两个菜单有共同的食物,我有这个例外。因为foodlist1中的food1 for menu1以前保存在数据库中,现在当food1添加到foodlist2并为menu2保存时,它有异常。我坚持,保存,保存或更新。实际上cascade.all或cascade.persist或without cascade。给我的建议是什么??

@Entity
public class Food {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private long price;

    public Food(String name, long price) {
        this.name = name;
        this.price = price;
    }
...//setter  and getter
}

@Entity
public class Menu {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    @Enumerated(value = EnumType.STRING)
    private MenuType menuType;
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Food> foodList = new ArrayList<>();

    public Menu(String name, MenuType menuType, List<Food> foodList) {
        this.name = name;
        this.menuType = menuType;
        this.foodList = foodList;
    }
...//setter  and getter
}

 public static void main(String[] args) {
        Food food1 = new Food("food_1", 45);
        Food food2 = new Food("food_2", 38);
        Food food3 = new Food("food_3", 30);

        List<Food> foodList1 = new ArrayList<>();
        foodList1.add(food1);
        foodList1.add(food2);

        List<Food> foodList2 = new ArrayList<>();
        foodList2.add(food1);
        foodList2.add(food3);

        Menu menu1 = new Menu("menu_1", MenuType.FASTFOOD, foodList1);
        Menu menu2 = new Menu("menu_2", MenuType.FASTFOOD, foodList2);

        MenuService menuService = new MenuService();
        menuService.persist(menu1);
        menuService.persist(menu2);

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题