Let's pretend that we want to build an eBay like app in which we have an entity named Customer and an entity named Order.

From a relational perspective, I would model this as:

Customer
+----+-----+
| ID | ... |
+----+-----+

Order
+----+-------------+-----+
| ID | CUSTOMER_ID | ... |
+----+-------------+-----+

Now when I want to map this to JPA, I have multiple choices:

  1. Create a uni-directional many-to-one association from Order to Customer. IMHO, this is the closest to the relational model. The downside is that in order to find all orders for a given customer I have to write a JPQL query as a customer does not know anything about its orders. Also I cannot in an OO natural way add a new order for a customer (e.g. customer.addOrder(aNewOrder);).

  2. Create a one-to-many association from the Customer to Order. This way in order to find all the orders for a given customer I can use customer.getOders() and I can add new orders for a customer in an OO natural way. The downside is that in order to find out the customer that has placed a given order I should use JPQL.

  3. Create a bidirectional one-to-many association from Customer to Order. This way I don't need to write any JPQL queries to retrieve all orders of a customer or the customer that has placed a given order. The downside is that is added complexity to maintain the bidirectional association.

As such I don't see a definite argument as to whether a unidirectional association has to be used or a bidirectional association is "correct". In other words it seems to me it all boils down to personal preference and taste of the designer/implementor of the model.

Am I right or are there rules according to which it is possible to determine the correct directionality for a given association?

Edit
Report