# Your First Cup: An Introduction to the Java EE Platform

# 4.2 Modifying the Java Persistence API Entity

The Java Persistence API allows you to create and use Java programming language classes that represent data in a database table. A Java Persistence API entity is a lightweight, persistent Java programming language object that represents data in a data store. To create or modify entities, or to remove them from the data store, call the operations of the Java Persistence API entity manager. To query entities, or to query the data encapsulated by the persistent fields or properties of a entity, use the Java Persistence Query Language (JPQL), a language similar to SQL that operates on entities.

In `firstcup-war`, there is a single entity that defines one query.

## 4.2.1 Edit the Constructor of the FirstcupUser Entity

Add code to the constructor for `FirstcupUser`.

1. Expand the Source Packages node, expand the `firstcup.entity` node, then double-click the `FirstcupUser.java` file to open it in the editor window.

2. Below the field definitions in the `FirstcupUser` class, add the following code in bold to the second, two-argument constructor:

           public FirstcupUser(Date date, int difference) {
               Calendar cal = new GregorianCalendar();
               cal.setTime(date);
               birthday = cal;
               ageDifference = difference;
           }

3. Right-click in the editor window and select Format.

## 4.2.2 Add a Named Query to the FirstcupUser Entity

Add a JPQL named query to the `FirstcupUser` entity that returns the average age difference of all `firstcup-war` users.

This query uses the `AVG` aggregate function to return the average of all the values of the `ageDifference` property of the `FirstcupUser` entities.

1. Directly before the class definition, copy and paste in the following code:

       @NamedQuery(name="findAverageAgeDifferenceOfAllFirstcupUsers",
       query="SELECT AVG(u.ageDifference) FROM FirstcupUser u")

   The `@NamedQuery` annotation appears just before the class definition of the entity and has two required attributes: `name`, with the unique name for this query; and `query`, the JPQL query definition.

2. Right-click in the editor window and select Format.

3. From the File menu, select Save.