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

  1. 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.
  1. Review the new OrderItem class which is mapped up to the new table

  2. Let's add a new mapping from an Order to the Customer who owns it. Open the Order class and add a new customer property which uses our Customer type.

  3. Add ManyToOne mapping along with an appropriate JoinColumn annotation on the new customer property which instructs JPA how to map an Order to a Customer based on the new field in the ORDER_T table

  4. 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

  5. After that is done you can add similar ManyToOne and JoinColumn mappings to add new order and product mappings to the OrderItem class

  6. Finally, let's also add a OneToMany mapping from Order to OrderItem to establish a bi-directional relationship between the Order and OrderItem classes (remember to keep track of which is the Owning and Inverse Side)

Verification

  1. Start the training application and go to the app home page

  2. 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.