Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Unbelievably, in 3 years nobody has answered your excellent question with examples of both ways to map the relationship.</p> <p>As mentioned by others, the "owner" side contains the pointer (foreign key) in the database. You can designate either side as the owner, however, if you designate the One side as the owner, the relationship will not be bidirectional (the inverse aka "many" side will have no knowledge of its "owner"). This can be desirable for encapsulation/loose coupling:</p> <pre><code>// "One" Customer owns the associated orders by storing them in a customer_orders join table public class Customer { @OneToMany(cascade = CascadeType.ALL) private List&lt;Order&gt; orders; } // if the Customer owns the orders using the customer_orders table, // Order has no knowledge of its Customer public class Order { // @ManyToOne annotation has no "mappedBy" attribute to link bidirectionally } </code></pre> <p>The only bidirectional mapping solution is to have the "many" side own its pointer to the "one", and use the @OneToMany "mappedBy" attribute. Without the "mappedBy" attribute Hibernate will expect a double mapping (the database would have both the join column and the join table, which is redundant (usually undesirable)).</p> <pre><code>// "One" Customer as the inverse side of the relationship public class Customer { @OneToMany(cascade = CascadeType.ALL, mappedBy = "customer") private List&lt;Order&gt; orders; } // "many" orders each own their pointer to a Customer public class Order { @ManyToOne private Customer customer; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload