0

Given the following JPA model:

@Entity
public class Customer {
    @Id    
    private long id;

    @OneToOne(mappedBy="customer")
    private ShippingAddress shippingAddress;

    //...
}

@Entity
public class ShippingAddress {
    @Id    
    private long id;

    @OneToOne
    private Customer customer;

    //...
}

This will create a foreign key to the customer table in the shipping_address table i.e. shipping_address.customer_id.

From a database point-of-view, one would say that customer is the parent table and shipping_address is the child table, because

  • An address cannot exist without a customer
  • If a customer is deleted, their address must also be deleted

However, according to JPA, the owner of this relationship is ShippingAddress because the JavaDoc for mappedBy states

This element is only specified on the inverse (non-owning) side of the association.

I find it extremely confusing that the owner of the relationship according to JPA is what (from the database point-of-view) would be considered the child table. Is there a way to reconcile this apparent contradiction?

Antonio Dragos
  • 1,973
  • 2
  • 29
  • 52
  • I agree with you that, in your example, `Customer` "owns" `Address`; but I think the JPA spec says `Address` "owns" the _relationship_. Sorta consistent with your argument, the relationship cannot exist without the `Address`. : ) – Brian Vosburgh Nov 25 '19 at 17:41

1 Answers1

0

In short: as posted before here and here, the owning side of the relation is the one that holds the FK in the DB table.

You can read this excellent answer for a full explanation why.

Repoker
  • 202
  • 3
  • 12