357 words

Step 3: Define an EJB Session Bean

Operations on the database will be performed by an instance of a session bean (EJB) class that we will define in this step:

  • Open the [New Session Bean] dialog box by right clicking the guest package node (in the [Projects] window), selecting New > Other... > Java EE (or Enterprise JavaBeans) > Session Bean and clicking Next.
  • Enter GuestDao as the EJB class name - use exactly that case sensitive class name.
  • The Java package name should be guest.
  • Click Finish to create the new session bean (EJB) class.

Now replace the content of the new source file with the following code:

package guest;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
public class GuestDao {
    // Injected database connection:
    @PersistenceContext private EntityManager em;
    // Stores a new guest: 
    public void persist(Guest guest) {
    // Retrieves all the guests:
    public List<Guest> getAllGuests() {
        TypedQuery<Guest> query = em.createQuery(
            "SELECT g FROM Guest g ORDER BY g.id", Guest.class);
        return query.getResultList();

The GuestDao session bean (EJB) class defines two methods:

  • persist - for storing a new Guest entity object in the database.
  • getAllGuests - for retrieving all the existing Guest objects from the database.

EJB classes are only supported by Java EE application servers such as GlassFish and JBoss, and not by servlet containers, such as Tomcat and Jetty.

By using EJB classes we can move some work from the application to the EJB container (i.e. to the application server). For instance, in this application the server:

  • Manages the instantiation of the EJB class and injects an instance of the EJB class into the servlet (as shown in the next step).
  • Prepares an EntityManager automatically and injects it into the em field (because it is annotated with the @PersistenceContext annotation).
  • Handles transactions automatically using JTA - no need to wrap every operation that modifies the database (such as persist) by transaction begin and commit.

The next step is adding a Servlet Class that will serve as the application controller.