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 Java Class] dialog box by right clicking the guest package node (in the [Package Explorer] window) and selecting New > Class.
- The package name should be guest.
- Enter GuestDao as the class name - use exactly that case sensitive class name.
- 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; @Stateless public class GuestDao { // Injected database connection: @PersistenceContext private EntityManager em; // Stores a new guest: public void persist(Guest guest) { em.persist(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 newGuestentity object in the database.getAllGuests- for retrieving all the existingGuestobjects 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
EntityManagerautomatically and injects it into theemfield (because it is annotated with the@PersistenceContextannotation). - Handles transactions automatically using JTA - no need to wrap every operation that modifies the database (such as
persist) by transactionbeginandcommit.
The next step is adding a Servlet Class that will serve as the application controller.