Exercise 06: Relationship Mappings - jkneal/spring-angular-train GitHub Wiki
Goals
We have several objects with some relationships which have natural relationships which we haven't established yet. For instance, an Order likely has a Customer who purchased the order. There is a new object called OrderItem in this exercise which will link up a Product to an Order and specify how many of that object the user has purchased in that order.
Instructions
- Review some changes made to the data model by looking in schema.sql. You'll notice the following:
- The ORDER_T table now has a CUSTOMER_ID column which contains the ID of a customer who owns the order
- There is a new ORDER_ITEM_T table which has ORDER_ID and PRODUCT_ID columns which link it up to the order the entry belongs to and the product which is included in the order respectively.
-
Review the new
OrderItemclass which is mapped up to the new table -
Let's add a new mapping from an
Orderto theCustomerwho owns it. Open theOrderclass and add a new customer property which uses ourCustomertype. -
Add ManyToOne mapping along with an appropriate JoinColumn annotation on the new customer property which instructs JPA how to map an
Orderto aCustomerbased on the new field in the ORDER_T table -
Modify the ManyToOne mapping on the customer so that it is fetched lazily so it doesn't retrieve that information unless we specifically ask for it
-
After that is done you can add similar ManyToOne and JoinColumn mappings to add new order and product mappings to the
OrderItemclass -
Finally, let's also add a OneToMany mapping from
OrdertoOrderItemto establish a bi-directional relationship between theOrderandOrderItemclasses (remember to keep track of which is the Owning and Inverse Side)
Verification
-
Start the training application and go to the app home page
-
Check out the various links for exercise 6 and investigate the data which is being returned. You should see order items and customer information returned along with the order and if you pay close attention to the URLs you will see that you can also retrieve customer and order item information as sub-resources under the orders resource.