JavaEJBIntroducing JEE Application Session Beans

Introducing JEE Application Session Beans

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Session beans represent the core business service objects that typically encapsulates business logic in an enterprise application. It is a Java component that either executes in a stand-alone EJB container or in a container that is a part of JEE application server. Session beans are generally used to model tasks that get user information from a client interface. The business logic associated with session beans also processes that information while maintaining the state of conversation with the client application. An EJB container provides the required services to the session from the background. The type of services that a session bean requires is either designated via Java annotation or via XML metadata. This article provides some key information to use session beans in an enterprise application.

Overview

In a typical three-tier architecture, a rich client front-end application provides an user interface for the end user to enter some data, such as user information for creating new account, credit card details for the payment of product purchased, and so forth, and triggers an event by submitting the information. This establishes a connection to the session bean residing in the EJB container. The communication is made with the help of a technique called remote method invocation (RMI). RMI helps in invoking the method that handles appropriate business logic associated with the client request. The session bean processes the request and validates the data in interaction with the back-end database server associated with the enterprise application. Finally, an appropriate response is sent to the client by the session bean in the form of a simple acknowledgement message or a data collection object or a simple object.

A client application may be developed by using JavaFX, Swing, or a simple POJO with console interaction, or it may be a Web application created using technologies like HTML, JavaScript, and so on. The point is that they all run on a desktop and provide only a user interface. A rich client provides a rich interface that gives the end user a very friendly experience. But, the responsibility of processing the event triggered by the client interface is taken up by the session beans. It holds the methods that define the business logic associated with the event.

Three-tier architecture
Figure 1: Three-tier architecture

Types of Session Beans

There are three types of session beans: stateful, stateless, and singleton.

  • Stateful: This type of session bean maintains conversational state information between the server and the client application. This means, when an EJB client gets an instance of this type of bean, the values associated with the instance remain consistent across the conversation. Any modification done on the instance variables will remain their values in successive method calls. The EJB container provides the service by persisting information during its passive state.  The state information is retrieved back by the container when it becomes active. Due to this act of persistence, the life cycle events are bit more complex in comparison to stateless session beans.
  • Stateless: Stateless session beans are rather simpler because they do not require saving any conversational state information on behalf of the client.
  • Singleton: This type of bean is created only once per application. As a result, they maintain the state information between client invocations throughout the duration the application lives.

Stateless Session Beans

Stateless session beans are nothing but POJOs designated by the @Stateless annotation. They may also be denoted in the ejb.jar.xml descriptor file with the help of XML metadata. An application can use both techniques simultaneously. In such a case, the XML metadata overrides any annotation used in the class-level.

A stateless session bean is always associated with a business interface. This interface contains the list of business method declaration defined by the session bean. The prototypes of the business methods are made available to the client application through this interface. The business interface is annotated as follows:

  • @Remote: This annotation designates that the business service is remotely available to the client. This is used when a client application runs on a different JVM from the one that runs the session bean in an EJB container.
  • @Local: This annotation denotes that the session bean is available locally. That means it is running on the same JVM that hosts the session bean with the EJB container.

If no annotation is specified in the business interface, by default it becomes a local business interface. It is quite possible that the application architecture uses both local and remote interfaces where some are designated as remote and some local, depending upon the requirement. Note that, since EJB 3.1, the session beans can expose their public members as a local view without the need of a separate business interface.

Session beans are often used as Data Access Objects (DAOs). They are used as a wrapper for JDBC calls or to obtain or modify JPA entities. Suppose we have a JPA entity as follows:

@Entity
public class Address implements Serializable {

   private static final long serialVersionUID = 1L;
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;
   private String street;
   private String city;
   private String zipCode;
   // ...
}

The business interface that corresponds to this JPA entity is:

import javax.ejb.Remote;

@Remote
public interface AddressDao {
   public void saveAddress(Address address);
   public Address getAddress(Long id);
   public void deleteAddress(Address address);
}

The session bean to implement the preceding business interface is as follows:

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class AddressDaoImpl implements AddressDao{

   @PersistenceContext
   private EntityManager em;

   @Override
   public void saveAddress(Address address) {
      if(address.getId()==null)
         saveNew(address);
      else
         updateExisting(address);

   }
   private void saveNew(Address address){
      em.persist(address);
   }
   private void updateExisting(Address address){
      em.merge(address);
   }

   @Override
   public Address getAddress(Long id) {
      return em.find(Address.class, id);
   }

   @Override
   public void deleteAddress(Address address) {
      em.remove(address);
   }
}

Stateful Session Beans

Stateful session beans are annotated with the @Stateful annotation and also can be denoted by XML metadata in the deployment descriptor file. Because stateful session beans maintain a consistent conversation state across multiple method calls, they provide additional functionality to notify before and after stages of transaction processing. This notification is used to manage data and cache by the EJB container. There are three types notification received by session bean from the EJB container. They are:

  • afterBegin: Indicates that a new transaction has begun.
  • beforeCompletion: Indicates that the transaction is about to commit.
  • afterCompletion: Indicates that the transaction has completed.

The business interface associated with stateful session beans is similar to stateless session beans and is annotated with the @Remote and @Local annotations in the same manner.

Therefore, the previous example of stateless session beans can be transformed into stateful session beans only by the change in the annotation provided in the bean class as follows:

import javax.ejb.Stateful;
// ...

@Stateful
public class AddressDaoImpl implements AddressDao{

   // ...
}

Singleton Session Beans

Singleton session beans were introduced in Java EE6. They are instantiated only once per application. Therefore, an enterprise application may have multiple stateless and stateful session beans; there can be only one instance of a singleton session bean for the full duration of the application. Though it maintains its state between client invocations, it cannot persist that state after the EJB container shuts down or crashes. In implementation, it is similar to stateless and stateful session beans and optionally can have one or more business interface.

Singleton beans are particularly useful to improve performance by caching frequently used database data. For example, we may modify the earlier example to fetch an address list in the following manner:

import javax.ejb.Remote;

@Remote
public interface AddressDao {
   public List<Address> getAddressList();
}

Now, modifying the bean class:

import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Singleton
public class AddressDaoImpl implements AddressDao{

   @PersistenceContext
   private EntityManager em;
   private List<Address> addressList=new ArrayList<>();

   @PostConstruct
   public void init(){
      Query query = em.createQuery("SELECT e
         FROM Employee e");
      addressList = query.getResultList();
   }

   @Override
   public List<Address> getAddressList() {
      return addressList;
   }
}

Because the bean is declared as a singleton, any invocation gets the same copy of the instance. This leverages performance because it is not required to fire multiple queries to the database upon each method invocation by the client.

Conclusion

This article avoids many other concepts associated with session beans, such as dependency injection, asynchronous method calls, life-cycle of session beans, and the like, to keep things simple for a basic understanding. Once the basic idea is grasped, delving deeper is just a matter of spending some time with session beans. As stated in the beginning, session beans are the core components of the JEE framework. Once one knows how to write session beans, it is not difficult to start developing an enterprise application because all the business logic of an enterprise application lies there.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories