JBoss EJB 3.0 and Extensions

  EntityManager Basics
Introduction

Since the EJB 3 entity beans are just POJOs, you can instantiate them using the new keyword. But to save and retrieve the object into and from the database table, you need an API known as the EJB 3.0 EntityManager. In this trail, we will cover how to get an EntityManager and its basic operations.

The sample application

In this trail, we implement the database-driven investment calculator application using the data model described in the last trail. Please click on the following buttons to add a few funds and investors now.

Click on the button below to launch the investment calculator program. The drop down lists are pre-populated with the funds and investors. Once you click on the "calculate" button, application retrieves the fund and investor details (e.g., fund growth rate, and the investor's start and end age), and uses the information to perform the calculation.

Obtain the EntityManager

As in earlier iterations of the calculator application, the CalculatorBean session bean handles all the business logic and provides an interface to the client (i.e., the servlet). So, all the entity bean manipulations are done inside the CalculatorBean class. The EntityManager object can be injected into the CalculatorBean via a @PersistenceContext annotation. That means you do not need to explicitly create or lookup the EntityManager object. Its value is automatically assigned by the EJB 3.0 container when you use it.


@Stateless
public class CalculatorBean implements Calculator {

  @PersistenceContext // (unitName="ejb3trail")
  protected EntityManager em;
  
  // ... ...
}

Note: If the application has multiple EntityManager configurations, each with a different database configuration, the unitName attribute in the @PersistenceContext annotation can be used to tell the container which EntityManager object to inject. For more on this topic, please refer to the "Configure Persistence Context" trail later in this hike.

Persist the entity bean object

The EntityManager.persist() method saves any entity bean instance to the database table as a new row. The code below shows how to create an entity bean, set its attributes, and then save it to the database.


@Stateless
public class EntityCalculator implements Calculator {

  @PersistenceContext
  protected EntityManager em;

  public void addFund (String name, double growthrate) {
    Fund fund = new Fund (name, growthrate);
    em.persist (fund);
  }

  public void addInvestor (String name, int start, int end) {
    Investor investor = new Investor (name, start, end);
    em.persist (investor);
  }

  // ... ...
}
Retrieve an entity bean

Saving the entity bean POJOs to database is only one side of the persistence operation. When the application needs to use those data, you would need to retrieve them from the database. The EntityManager.find() method retrieves an entity bean instance from the database using the entity bean class name (i.e., the database table name) and the entity ID (i.e., the database primary key). In our O/R mapping schema, the entity ID is the Id attribute of the entity bean instance. The following code segment in CalculatorBean shows how to use EntityManager.find().


@Stateless
public class EntityCalculator implements Calculator {

  @PersistenceContext
  protected EntityManager em;
  
  // ... ...
  
  public double calculate (int fundId, int investorId, double saving) {

    Investor investor = 
        em.find(Investor.class, 
                Integer.valueOf(investorId));
    Fund fund = 
        em.find(Fund.class, 
                Integer.valueOf(fundId));

    int start = investor.getStartAge();
    int end = investor.getEndAge();
    double growthrate = fund.getGrowthrate();

    // ... ...

    TimedRecord rec = 
        new TimedRecord (fund, investor, saving, result, ts);
    em.persist (rec);

    return result;
  }

}

Finding and retrieving entity beans based on the primary ID is easy. But the problem is that you do not always know the primary ID of the data row you are looking for. In this trail, we have so far ignored how we obtained a list of Fund and Investor entity beans from the database with their primary IDs and names. We will cover that in the next trail.

The complete source code reference

Session bean that persists and retrieves Fund and Investor beans to/from the database.

You can ignore the getFunds() and getInvestors() methods in the CalculatorBean class for now. They will be discussed in a later trail covering the EJB query language.

The JSP user interface

Summary

In this trail, you learned how to create, save, and retrieve an entity bean. A key feature of the database is that it allows you to search and retrieve the data using a query language, including to retrieve all the rows of a specific table (i.e., the Fund or Investor tables in our application). The EntityManager supports advanced database queries. We will look into that in the next trail.