我在订单项中遇到问题
order_id
它为空,因为我在订单中创建 OrderItems
,就像订单的 JSON
{
"supplier": {
"supplierId": 1,
"supplierName": "yahya",
"country": "Algeria",
"region": "undefined",
"productIds": [142, 141]
},
"orderItems": [
{
"productId": 1,
"quantity": 2,
"order_price": 10
},
{
"productId": 2,
"quantity": 1,
"order_price": 15
}
],
"orderType": "IMPORT",
"orderDate": "2024-05-10",
"reference": "ABC123",
"total_price": 35
}
package com.example.importexportservice.models;
import jakarta.persistence.*;
@Entity
@Table(name = "order_item")
public class OrderItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "order_item_id")
private Long id;
@ManyToOne
@JoinColumn(name = "order_id")
private Order order;
@Column(name = "product_id")
private Long productId;
@Column(name = "quantity")
private int quantity;
@Column(name = "Order_price")
private int Order_price;
public OrderItem() {
}
public OrderItem(Long id, Order order, Long productId, int quantity, int order_price) {
this.id = id;
this.order = order;
this.productId = productId;
this.quantity = quantity;
this.Order_price = order_price;
}
}
package com.example.importexportservice.models;
import jakarta.persistence.*;
import java.util.Date;
import java.util.List;
@Entity
@Table(name = "order_table")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "order_id")
private Long orderId;
@ManyToOne
@JoinColumn(name = "supplier_id")
private Supplier supplier;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL ,fetch = FetchType.EAGER)
private List<OrderItem> orderItems;
public List<OrderItem> getOrderItems() {
return orderItems;
}
public void setOrderItems(List<OrderItem> orderItems) {
this.orderItems = orderItems;
}
@Enumerated(EnumType.STRING)
@Column(name = "order_Type")
private OrderType orderType;
public Order(Long orderId, Supplier supplier, List<OrderItem> orderItems, OrderType orderType, Date orderDate, String reference, int total_price) {
this.orderId = orderId;
this.supplier = supplier;
this.orderItems= orderItems;
this.orderType = orderType;
this.orderDate = orderDate;
this.reference = reference;
Total_price = total_price;
}
@Temporal(TemporalType.DATE)
@Column(name = "order_date")
private Date orderDate;
@Column(name = "order_reference")
private String reference;
@Column(name = "order_Total_price")
private int Total_price;
public Order() {
}
}
所以我在 orderitem 中发现订单 id 为空,即使我尝试在构造函数中循环列表并影响订单 id,但我仍然发现它为空。是我的映射错误还是我可以做其他事情?
我们可以通过多种方式解决这个问题。在这里我解释其中 1 个。
您必须在 Order 和 OrderItem POJO 类中进行更改。 从 OrderItem 中删除
private Order order;
,然后在 Order 中只需将 @OneToMany
注释替换为
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "order_id", referencedColumnName = "order_id")
你也可以参考这个Gist