Chapter 13. Implementing Unidirectional Non-Functional Associations with Java, JPA and JSF

Table of Contents

1. Implementing Multi-Valued Reference Properties in Java
2. Make a JPA Entity Class Model
3. New issues
4. Write the Model Code
4.1. Summary
4.2. Encode the entity classes
4.3. Implement a deletion policy
4.4. Serialization and De-Serialization
5. Write the User Interface Code
5.1. Show information about associated objects in the List Objects use case
5.2. Allow selecting associated objects in the create use case
6. Run the App and Get the Code
7. Possible Variations and Extensions
7.1. Set-valued versus ordered-set-valued reference properties

A unidirectional non-functional association is either one-to-many or many-to-many. In both cases such an association is represented, or implemented, with the help of a multi-valued reference property.

In this chapter, we show

  1. how to derive a data model in the form of a JPA entity class model from an information design model with multi-valued reference properties representing unidirectional non-functional associations,

  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 model code.

1. Implementing Multi-Valued Reference Properties in Java

A multi-valued reference property, such as Book::authors, allows storing a collection of references to objects of some type, such as references to Author objects. When creating a new object of type Book, it must be possible to assign one or more authors to the book. to assign the constructor needs an extra parameter for the multi-valued reference property. In general, we can allow this value to be a set (or list) of internal object references or of ID references. However, using JPA there is no need for ID references, being very easy to use object references:

@Entity @Table( name="books")
@ManagedBean( name="book")
@ViewScoped
public class Book {
  ...
  private Set<Author> authors;
  
  public Book() { // required by JPA @Entity annotation!}
  public Book( String isbn, String title, Integer year, Publisher publisher, Set<Author> authors) {...}

  public Set<Author> getAuthors() { return this.authors;}
  public void setAuthors( Set<Author> authors) { this.authors = authors;}
  ...
}