Your First Cup: An Introduction to the Java EE Platform

ProcedureAdd a Business Method to DukesBirthdayBean that Gets the Average Age Difference of firstcup Users

Once the FirstcupUser entity is complete, add a business method to the DukesBirthdayBean session bean to call the named query that returns the average age difference of all users.

  1. Double-click DukesBirthdayBean in the Projects Pane under Enterprise Beans.

  2. Below the class definition, add a @PersistenceContext annotation and field of type EntityManager:

    private EntityManager em;
  3. Right-click in the Editor window, select Insert Code, then Add Business Method.

  4. In the Add Business Method dialog, enter getAverageAgeDifference under Name, set the Return Type to Double, and click OK.

  5. Replace the body of the newly created getAverageAgeDifference method with the following code:

    public Double getAverageAgeDifference() {
        Double avgAgeDiff = (Double) 
            .getSingleResult();"Average age difference is: " + avgAgeDiff);
        return avgAgeDiff; 

    The named query in FirstcupUser is called by using the EntityManager's createNamedQuery method. Because this query returns a single number, the getSingleResult method is called on the returned Query object. The query returns a Double.

  6. Select File -> Save.