Multiple @ManyToOne fields pointing to same entity in JPA / Hibernate

前端 未结 1 1398
一生所求
一生所求 2020-12-09 20:05

I have an Order entity that has a billingAddress and a shippingAddress. I also have an Address entity. I am trying to mak

相关标签:
1条回答
  • 2020-12-09 20:07

    Regarding your first question: is it a ManyToOne?

    It depends. If several orders can have the same shipping address, then it's a ManyToOne. If only one order can have a given shipping address, then it's a OneToOne. Same for billing address.

    I'm not sure making the association bidirectional is a good idea. I probably wouldn't do it in this case. But if you want to make it bidirectional, then you have to make them bidirectional. You indeed have two different associations here. The mapping would thus look like the following:

    @OneToMany(mappedBy = "shippingAddress")
    private Set<Order> shippedOrders;
    
    @OneToMany(mappedBy = "billingAddress")
    private Set<Order> billedOrders;
    

    or, if the association is in fact a OneToOne (see answer to the first question):

    @OneToOne(mappedBy = "shippingAddress")
    private Order shippedOrder;
    
    @OneToOne(mappedBy = "billingAddress")
    private Order billedOrder;
    
    0 讨论(0)
提交回复
热议问题