罗斯文(Northwind)-创建订单(MySQL + Spring引导)

时间:2018-10-30 19:29:37

标签: spring hibernate spring-boot spring-data-jpa

我有具有以下架构的数据库: enter image description here

我想创建一个订单。我用以下所有列创建了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获取所有Orders时,我可以看到对于每个orderOrderDetails值都是空的。

这是我的示例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!

您能帮我吗?

2 个答案:

答案 0 :(得分:0)

您可以尝试以FetchMode JOIN 关系加入表。

@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
@Fetch(FetchMode.JOIN)
private Set<OrderDetails> orderDetails;

答案 1 :(得分:0)

@ManyToOne(cascade = CascadeType.PERSIST)添加到Order实体的OrderDetails字段中,这样,休眠状态将在保存两个实体时知道如何连接这两个实体。

createOrUpdateOrder方法将如下所示:

public Integer createOrUpdateOrder(Order order){
    Order newOrder = orderRepository.save(order);
    return newOrder.getOrderID();
}