Chapter 12. Implementing Enumeration Attributes in a Java EE Web App

Table of Contents

1. New Issues
2. Make an Entity Class Model
3. Write the Model Code
3.1. Code the enumerations
3.2. Code the JPA entity class
3.3. Define a converter for serializing enumeration attribute values
3.4. Code the enumeration attribute setters
3.5. Write a serialization function
3.6. Database schema
3.7. Creating test data
4. Write the View Code
4.1. Selection lists
4.2. Radio button groups and checkbox groups
5. Displaying Value Sets for Multi-Valued Enumeration Attributes
6. Run the App and Get the Code
7. Practice Projects
7.1. Project 1 - Adding ratings and genres as enumeration attributes
7.2. Project 2 - Adding country codes and religions as enumeration attributes
8. Quiz Questions
8.1. Question 1: JPA custom converter implementation class
8.2. Question 2: Cardinality constraints for enum attributes
8.3. Question 3: JPA enum attribute serialization annotation
8.4. Question 4: JSF single-valued enum attribute
8.5. Question 5: JSF multi-valued enum attribute

In this chapter, we show how to build a back-end web application with enumeration attributes, using Java with JPA and JSF. In addition to the topic of enumeration attributes, we also show how to deal with multi-valued attributes.

1. New Issues

Compared to the Validation App discussed in Chapter 9, we now deal with the following new issues:

  1. Enumeration datatypes have to be defined in a suitable way as part of the model code.

  2. Enumeration attributes have to be defined in model classes and handled in the user interface with the help of suitable choice widgets.

In terms of coding, the new issues are:

  1. In the model code we have to take care of

    1. enumerations to be defined in the form of Java enum classes;

    2. single-valued enumeration attributes, like Book::originalLanguage, requiring the JPA annotation @Enumerated for defining the conversion between Java enumeration literals and corresponding database table column values;

    3. multi-valued enumeration attributes, like Book::publicationForms, requiring the JPA annotation @Convert with suitable arguments defining a JPA custom converter for (de-)serializing collections of Java enumeration literals;

    4. extending the methods Book.create, and Book.update such that they take care of the enumeration attributes.

  2. In the user interface code we have to take care of

    1. adding new table columns in retrieveAndListAll.xhtml;

    2. adding suitable choice widgets in create.xhtml and upate.xhtml;

    3. rendering multi-valued enumeration attributes in the table view of retrieveAndListAll.xhtml and in the choice widgets of create.xhtml and upate.xhtml (with the help of an array of JSF SelectItems, each consisting of an enumeration value and its label).