public FirstcupUser(Date date, int difference) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
birthday = cal;
ageDifference = difference;
}
Java Platform, Enterprise Edition (Java EE) 8 Your First Cup: An Introduction to the Java EE Platform |
Previous | Next | Contents |
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.
Add code to the constructor for FirstcupUser
.
Expand the Source Packages node, expand the firstcup.entity
node,
then double-click the FirstcupUser.java
file to open it in the editor
window.
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;
}
Right-click in the editor window and select Format.
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.
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.
Right-click in the editor window and select Format.
From the File menu, select Save.
Previous | Next | Contents |