我有一个简单的Order实体,它包含一个带有Dishes列表的OneToMany关系。
Order实体:
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Table(name = "orders")
@ToString
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Enumerated(EnumType.STRING)
private Status status;
private LocalDateTime creationDate;
private LocalDateTime updateDate;
private BigDecimal totalPrice;
private String address;
@ManyToOne(fetch = FetchType.LAZY)
@ToString.Exclude
private User user;
@OnDelete(action = OnDeleteAction.CASCADE)
@OneToMany(
mappedBy = "order",
cascade = CascadeType.ALL,
orphanRemoval = true)
@ToString.Exclude
private List<Dish> dishes;
public Order(long id, Status status, BigDecimal totalPrice, String address, List<Dish> dishes) {
this.id = id;
this.status = status;
this.creationDate = LocalDateTime.now();
this.updateDate = LocalDateTime.now();
this.totalPrice = totalPrice;
this.address = address;
this.dishes = dishes;
}
}Dish实体:
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class Dish {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String description;
private Category category;
BigDecimal price;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@ToString.Exclude
private Order order;
public Dish(long id, String name, String description, Category category, BigDecimal price) {
this.id = id;
this.name = name;
this.description = description;
this.category = category;
this.price = price;
}
public void setOrder(Order order) {
this.order = order;
order.addDish(this);
}
}在这里,我试着保存这些盘子的订单。
Dish dish1 = new Dish(0, "Dish first", "Description of first Dish", Category.SNACKS, BigDecimal.valueOf(100));
Dish dish2 = new Dish(0, "Dish second", "Description of second Dish", Category.BURGERS, BigDecimal.valueOf(100));
List<Dish> dishes1 = Arrays.asList(dish1, dish2);
List<Dish> dishes2 = Arrays.asList(dish2);
Order order1 = new Order(0, Status.PENDING, BigDecimal.valueOf(150), "Address 1", dishes1);
Order order2 = new Order(0, Status.COMPLETED, BigDecimal.valueOf(150), "Address 2", dishes2);问题是,菜品与订单一起保存,但不与Order实体关联。Id为空

我知道我在创建菜品时没有设置order字段,但是如果我需要同时保存点菜和菜品,该如何做。
发布于 2022-02-06 18:16:21
您有错误的模型,您期望在dish2是什么?秩序和迪什之间的关系不是一对多,而是多对多.Hibernate不知道在列中输入什么。
https://stackoverflow.com/questions/70971629
复制相似问题