Sunday, May 10, 2015

EJB Interview Questions

What are benefits of using EJB ?
  • The development of EJB applications is easy as the business logic is separated by the application developer and at the same time the developer can utilize the services of the EJB container.
  • Application Server/ EJB container provides most of the system level services like transaction handling, logging, load balancing, persistence mechanism, exception handling and so on. Developer has to focus only on business logic of the application.
  • EJB container manages life cycle of ejb instances thus developer needs not to worry about when to create/delete ejb objects. 
  • The EJB architecture is compatible with other APIs like servlets and JSPs.
  • EJB allows to build applications using two different layered architectures: the traditional four-tier architecture and domain-driven design (using EJB3). Such isolation of components makes it easy to develop, deploy and manage EJB applications.

What are benefits of using EJB 3 ?
  • It offers seamless integration with other J2ee technologies and a complete stack of server solutions, including persistence, messaging, lightweight scheduling, remoting, web services, dependency injection (DI), and interceptors.
  • EJB 3 enables to develop an EJB component using POJOs and POJIs that know nothing about platform services.
  • EJB 3 allows us to use metadata annotations to configure a component instead of using XML deployment descriptors.
  • JNDI lookups have been turned into simple configuration using metadata-based dependency injection (DI). E.g. @EJB annotation injects EJB into the annotated variable.
  • EJB 3 components are POJOs, and can be easily be executed outside the container using testing frameworks such as JUnit or TestNG.

What are the different types of EJB ?
There are three types of EJB beans, Entity Bean, Session Bean and Message Driven Bean(MDB).

Session Beans: A session bean encapsulates business logic that can be invoked programmatically by a client over local, remote, or web service client views. A session bean instance is available only for the duration of a “unit of work” and is not persistent hence it does not survive a server crash or shutdown. There are two types of session beans: Stateful and Stateless Session Beans.
  • Stateful Session Bean: A stateful session bean automatically saves bean state between client invocations. In a stateful session bean, the instance variables represent the state of a unique client/bean session. Since the client interacts with the bean, such state is often called the conversational state. A session bean is not shared and it can have only one client. When the client terminates, its session bean appears to terminate and is no longer associated with the client. The state is retained for the duration of the client/bean session. If the client removes the bean, the session ends and the state disappears.
  • Stateless Session Bean: A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client but only for the duration of the invocation. When the method is finished, the client-specific state should not be retained. Clients although can change the state of instance variables in pooled stateless beans, and this state is held over to the next invocation of the pooled stateless bean. Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client. Because they can support multiple clients, stateless session beans can offer better scalability for applications that require large numbers of clients. A stateless session bean can implement a web service, but a stateful session bean cannot.
@Remote
public interface InventorySessionBeanRemote {
   //add business method declarations
}

@Stateful
public class InventorySessionBean implements InventorySessionBeanRemote {
   //implement business method 
}

@Stateless
public class InventorySessionBean implements InventorySessionBeanRemote {
   //implement business method 
}

Message Driven Beans: A message-driven bean is an enterprise bean that allows Java EE applications to process messages asynchronously. This type of bean normally acts as a JMS message listener which receives and processes JMS messages or other kinds of messages. Clients never invoke MDB methods directly. The message-driven beans unlike session beans are not accessed by the clients through interfaces, but directly using a bean class. Below are some aspects of MDB's:
  • A message-driven bean’s instances retain no data or conversational state for a specific client, hence are stateless.
  • All instances of a message-driven bean are equivalent, allowing the EJB container to assign a message to any message-driven bean instance. The container can pool these instances to allow streams of messages to be processed concurrently.
  • A single message-driven bean can process messages from multiple clients.
  • Message-driven beans are transaction aware and are relatively short-lived.
@MessageDriven(
   name = "QueueMessageHandler",
   activationConfig = {
      @ActivationConfigProperty( propertyName = "destinationType", 
                                 propertyValue = "javax.jms.Queue"),
      @ActivationConfigProperty( propertyName = "destination", 
                                 propertyValue ="/queue/InfoQueue")
   }
)
public class InventoryMessageBean implements MessageListener {
 
   // general purpose annotation used to inject anything that the container knows about.
   @Resource
   private MessageDrivenContext mdbContext;  
 
   // injects the dependency as ejb instance into another ejb
   @EJB
   InventoryPersistentBeanRemote inventoryBean;
 
   public InventoryMessageBean(){        
   }
 
   public void onMessage(Message message) {
   }
} 

Entity Beans: An entity bean is a simple POJO having mapping with table. They are used to model persistent data objects. The Entities model lower-level application concepts that high-level business processes manipulate. Entities are object oriented representations of the application data stored in the database and hence survives container crashes and shutdown. JPA entities support OO capabilities, including relationships between entities, inheritance, and polymorphism. Entity beans are transactional.
    The @Entity annotation marks the particular java class as an ejb entity and a persistent object representing the data-store record which is preferred to be serializable. The EntityManager interface reads the ORM metadata for an entity and performs persistence operations. It has the know how to add entities to the database, update stored entities, and delete and retrieve entities from the database. It also helps to execute queries using Query interface. The persistence unit is a reference to the data source in order to access the database. It contains the configuration such as the type of database  and if database tables should be automatically created by the persistence engine.

@Entity
@Table(name="items")
public class Item implements Serializable{
    
   private int id;
   private String name;

   public Item(){ }

   //mark id as primary key with autogenerated value
   //map database column id with id field
   @Id
   @GeneratedValue(strategy= GenerationType.IDENTITY)
   @Column(name="id")
   public int getId() {
      return id;
   }
   ...
}

@Stateless
public class InventoryPersistentBean implements InventoryPersistentBeanRemote {
 
   //pass persistence unit to entityManager.
   @PersistenceContext(unitName="EjbComponentPU")
   private EntityManager entityManager;         

   public void addItem(Item item) {
      entityManager.persist(item);
   }    

   public List<item> getItems() {        
      return entityManager.createQuery("From Items").getResultList();
   }
   ...
}

Explain the life cycle of EJB beans ?
Each type of enterprise bean (stateful session, stateless session, or message-driven) has a different lifecycle.

Lifecycle of a Stateful Session Bean:
  • The client initiates the lifecycle by obtaining a reference to a stateful session bean instance through dependency injection or JNDI lookup.
  • The container performs any dependency injection as specified by metadata annotations on the bean class or by the deployment descriptor.
  • It then calls the PostConstruct lifecycle callback interceptor method(s) for the bean, if any.
  • The container then returns the session object reference to the client. The instance is now in the method ready state and ready for client’s business methods.
  • In the ready stage, the EJB container may decide to deactivate, or passivate, the bean by moving it from memory to secondary storage. The EJB container invokes the method annotated @PrePassivate, if any, immediately before passivating it. If a client invokes a business method on the bean while it is in the passive stage, the EJB container activates the bean, calls the method annotated @PostActivate, if any, and then moves it to the ready stage.
  • At the end of the lifecycle, the client invokes a method annotated @Remove, and the EJB container calls the method annotated @PreDestroy, if any. The bean’s instance is then ready for garbage collection.
     
A business method is executed either in a transaction context or with an unspecified transaction context. When the session bean instance is included in a transaction, the container issues the afterBegin method on it before the business method and the instance becomes associated with the transaction. The container issues beforeCompletion before transaction commit and afterCompletion when the transaction completes.

Lifecycle of a Stateless Session Bean:
  • The container invokes the newInstance method on the session bean class to create a new session bean instance.
  • It then performs any dependency injection as specified by metadata annotations on the bean class or by the deployment descriptor.
  • The container then calls the @PostConstruct lifecycle callback interceptor methods for the bean, if any.
  • The container creates the instance of session bean which is then ready to be delegated a business method call from the clients or a call from the container to a timeout callback method.
  • When the container no longer needs the instance it invokes the @PreDestroy callback interceptor methods, if any. This ends the life of the stateless session bean instance, and the bean’s instance is ready for garbage collection.. 

Lifecycle of a Message Driven Bean:
The EJB container usually creates a pool of message-driven bean instances. For each instance, the EJB container performs following tasks.
  • If the message-driven bean uses dependency injection, the container injects these references before instantiating the instance.
  • The container calls the method annotated @PostConstruct, if any.
  • Like a stateless session bean, a message-driven bean is never passivated and has only two states: nonexistent and ready to receive messages.
At the end of the lifecycle, the container calls the method annotated @PreDestroy, if any. The bean’s instance is then ready for garbage collection.

No comments:

Post a Comment