Northwind - 创建订单(MySQL + Spring启动)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Northwind - 创建订单(MySQL + Spring启动)相关的知识,希望对你有一定的参考价值。
我想创建一个订单。我用下面的所有列创建了Order的DAO,并添加了这样的关系:
订购
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name ="OrderID", nullable = false,unique = true)
private Integer orderID;
// here attributes from Columns I am skipping it
@ManyToOne
@JoinColumn(name = "customerID", insertable = false, updatable = false)
@JsonIgnore
private Customer customer;
public Customer getCustomer() {
return this.customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
private Set<OrderDetails> orderDetails;
public Set<OrderDetails> getOrderDetails() {
return orderDetails;
}
public void setOrderDetails(Set<OrderDetails> orderDetails) {
this.orderDetails = orderDetails;
}
我现在想知道如何使用订单详细信息创建POST。我这样试过:
OrderService
public void createOrUpdateOrder(Order order){
Set<OrderDetails> orderDetailsSet = new HashSet<>();
for( OrderDetails orderDetails : order.getOrderDetails() ) {
orderDetails.setOrder( order );
orderDetails.setOrderID(order.getOrderID()); // HERE IS NULL, orderID is not set yet, maybe thats the reason
}
order.setOrderDetails( orderDetailsSet );
orderRepository.save(order);
}
但是当我使用OrderDetails获取所有订单时,我可以看到每个订单orderDetails值为空。
这是我的示例POST有效负载:
{
"customerID":"ANATR",
"employeeID": 3,
"orderDate": "1996-07-10",
"requiredDate": "1996-07-24",
"shippedDate": "1996-07-16",
"shipVia": 2,
"freight": 58.17,
"shipName": "Hanari Carnes",
"shipAddress": "Rua do Paço, 67",
"shipCity": "Rio de Janeiro",
"shipRegion": "RJ",
"shipPostalCode": "05454-876",
"shipCountry": "Brazil",
"orderDetails":[
{
"unitPrice": 9,
"quantity": 10,
"discount": 0,
"productID":12
}
]
}
以及我对GET订单的回复:
"orderID": 1000019,
"customerID": "ANATR",
"employeeID": 3,
"orderDate": "1996-07-10",
"requiredDate": "1996-07-24",
"shippedDate": "1996-07-16",
"shipVia": 2,
"freight": 58.17,
"shipName": "Hanari Carnes",
"shipAddress": "Rua do Paço, 67",
"shipCity": "Rio de Janeiro",
"shipRegion": "RJ",
"shipPostalCode": "05454-876",
"shipCountry": "Brazil",
"orderDetails": [] <----- should not be empty!
你能帮帮我吗?
答案
你可以尝试使用FetchMode JOIN关系加入表。
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
@Fetch(FetchMode.JOIN)
private Set<OrderDetails> orderDetails;
另一答案
将@ManyToOne(cascade = CascadeType.PERSIST)
添加到Order
实体中的OrderDetails
字段,这样hibernate将知道在保存这两个实体时如何连接这两个实体。
然后createOrUpdateOrder
方法看起来像这样:
public Integer createOrUpdateOrder(Order order){
Order newOrder = orderRepository.save(order);
return newOrder.getOrderID();
}
以上是关于Northwind - 创建订单(MySQL + Spring启动)的主要内容,如果未能解决你的问题,请参考以下文章
Northwind数据库不能在SQL Server 2012上创建