Spring-Northwind MySQL中的一对多

时间:2018-10-15 15:06:41

标签: hibernate spring-boot northwind

我想像下面给出的模式那样实现订单和客户之间的一对多关系:enter image description here

在我的数据库中,我实现了相同的架构。我想设置OneToMany关系,并最终像这样使用JSON对/ {customerID} GET做出响应:

customerID: "test",
companyName: "testCompany",
...
...
orders: [ 
        { orderID: 123,
           ...//other keys for orderObj
           ...
}]

但是我不知道如何实现这一目标。我尝试过这种方式:

// ORDER CLASS
@Entity
@Table(name="Orders")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Order {
    @Id
    private Integer orderID;
    private String customerID;
    private Integer employeeID;
    private String orderDate;
    private String requiredDate;
    private String shippedDate;
    private Integer shipVia;
    private Float freight;
    private String shipName;
    private String shipAddress;
    private String shipCity;
    private String shipRegion;
    private String shipPostalCode;
    private String shipCountry;

    @ManyToOne
    @JoinColumn(name="customerID", insertable=false, updatable=false)
    private Customer customer;
    public Customer getCustomer(){
        return  this.customer;
    }

    public void setCustomer(Customer customer){
        this.customer=customer;
    }

我的客户类别:

// CUSTOMER
@Entity
@Table(name="Customers")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Customer  {

    @Id
    private String customerID;
    private String companyName;
    private String contactName;
    private String contactTitle;
    private String address;
    private String city;
    private String region;
    private String postalCode;
    private String country;
    private String phone;
    private String fax;

    @OneToMany(mappedBy = "customerID")
    private Set<Order> orders;
    public Set<Order> getOrders(){
        return orders;
    }
    public void setOrders(Set<Order> orders) {
        this.orders = orders;
    }

然后在我的控制器中

//reads one customer
@GetMapping(value = "/{customerId}")
public  Customer getCustomer(@PathVariable String customerId) {
    return customerRepository.findById(customerId).get();
}

问题是不起作用。你能给我提些建议吗?

0 个答案:

没有答案