Chapter 15. Implementing Bidirectional Associations with Java, JPA and JSF

Table of Contents

1. Make a JPA Entity Class Model
2. Write the Model Code
2.1. New issues
2.2. Summary
2.3. Encode each class of the data model as an entity class
2.4. Encode the setter operations
2.5. Encode the add and remove operations
2.6. Take care of deletion dependencies
2.7. EntityManagers and Cached Entities
3. Exploiting Derived Inverse Reference Properties in the User Interface
3.1. Show information about published books in the List Publishers use case
4. Run the App and Get the Code

In this chapter of our tutorial, we show

  1. how to derive a data model in the form of a JPA entity class model from an information design model,

  2. how to encode the JPA entity class model in the form of entity classes (representing model classes),

  3. how to write the view and controller code based on the entity classes.

1. Make a JPA Entity Class Model

The starting point for making a JPA entity class model is an information design model like the following one:

Notice that there are two bidirectional associations, each of them having two opposite association end dots corresponding to a pair of mutually inverse reference properties:

  1. The first pair is Book::publisher and Publisher::/publishedBooks.

  2. The second pair is Book::authors and Author::/authoredBooks.

Since books are entities that existentially depend on authors and possibly on publishers, and not the other way around, it's natural to maintain the master references in book objects, and consider the inverse references in publisher and author objects as derived (or slave) data. Therefore, we define publishedBooks and authoredBooks as derived inverse reference properties, which is indicated by their slash prefix in the JPA entity class model.

We now show how to derive a Java data model from this design model:

  1. Turn the «stdid» stereotype into the UML property modifier {id}.

  2. Replace the two association lines between Publisher and Book, and between Book and Author, by the two pairs of mutually inverse reference properties Book::publisher and Publisher::/publishedBooks as well as Book::authors and Author::/authoredBooks.

  3. Add the following UML property modifiers for indicating the multiplicity of reference properties:

    • oneToMany to the derived reference property Publisher::/publishedBooks,

    • manyToOne to the reference property Book::publisher

    • manyToMany to the reference property Book::authors

    • manyToMany to the derived reference property Author::/authoredBooks

  4. Create a set and a get operation for each derived and non-derived single-valued and multi-valued property.

  5. Create an add, and a remove operation for each derived and non-derived multi-valued property.

This leads to the following JPA entity class model:

Figure 15.1. The Java data model