Google News
logo
EJB Interview Questions
EJB stands for "Enterprise Java Beans". EJB is an essential part of a J2EE platform. J2EE platform have component based architecture to provide multi-tiered, distributed and highly transactional features to enterprise level applications.
 
EJB provides an architecture to develop and deploy component based enterprise applications considering robustness, high scalability and high performance. An EJB application can be deployed on any of the application server compliant with J2EE 1.3 standard specification.
There are three types of enterprise bean in java.
 
Entity Bean : Entity Bean is a server-side component that represents the persistent data. Since EJB 3.x, it is replaced by JPA.

Session Bean : Session Bean encapsulates business logic. It can be invoked by local, remote or web service client. There are 3 types of session bean.
    * Stateless Session Bean
    * Stateful Session Bean
    * Singleton Session Bean
Message Driven Bean : Message Driven Bean (MDB) encapsulates business logic. It is invoked by passing the message. It is like JMS receiver.
A stateful session bean is a type of enterprise bean which preserve the conversational state with client. A stateful session bean as per its name keeps associated client state in its instance variables. EJB Container creates a separate stateful session bean to process client's each request. As soon as request scope is over, statelful session bean is destroyed.
A stateless session bean is a type of enterprise bean which is normally used to do independent operations. A stateless session bean as per its name does not have any associated client state, but it may preserve its instance state. EJB Container normally creates a pool of few stateless bean's objects and use these objects to process client's request. Because of pool, instance variable values are not guaranteed to be same across lookups/method calls.
A singleton session bean is instantiated once per application and exists for the lifecycle of the application. Singleton session beans are designed for circumstances in which a single enterprise bean instance is shared across and concurrently accessed by clients.
 
Singleton session beans offer similar functionality to stateless session beans but differ from them in that there is only one singleton session bean per application, as opposed to a pool of stateless session beans, any of which may respond to a client request. Like stateless session beans, singleton session beans can implement web service endpoints.
 
Singleton session beans maintain their state between client invocations but are not required to maintain their state across server crashes or shutdowns.
JMS stands for Java Message Service. JMS API is a Java API which contains a common set of interfaces to implement enterprise based messaging systems. JMS API is used to implement Messaging systems in Java-based applications only, it does not support other languages.
 
JMS API is used to create, send, receive and read messages or exchange messages between different systems. Once we develop a Java Messaging System with JMS API, then we can deploy the same application in any JMS Provider software.
A Message-Driven Bean (MDB) is a Java Messaging Service (JMS) message listener that can reliably consume messages from a queue or a subscription of a topic. The advantage of using an MDB instead of a JMS message listener is that you can use the asynchronous nature of a JMS listener with the benefit of the EJB container performing the following :
 
* The consumer is created for the listener. That is, the appropriate QueueReceiver or TopicSubscriber is created by the container.
* The MDB is registered with the consumer. The container registers the MDB with the QueueReceiver or TopicSubscriber and its factory at deployment time.
* The message acknowledgment mode is specified.

An MDB is an easy method for creating a JMS message listener.
 
MDB Overview : 
 
An MDB is a unique EJB whose function is to read or write JMS messages from a JMS Destination (topic or queue).
 
The OC4J MDB interacts with Oracle JMS, which must be installed and configured appropriately. Oracle JMS is installed and configured on an Oracle database. Within this database, the appropriate queue or table is created.
 
* The MDB opens a JMS connection to the database using a data source with a username and password. The data source represents the Oracle JMS resource provider and uses a JDBC driver to facilitate the JMS connection.
* The MDB opens a JMS session over the JMS connection.
* Any message for the MDB is routed to the onMessage method of the MDB from the queue or topic. Other clients may have access to the same queue or topic to put on messages for the MDB.
Session Facade is a design pattern to access enterprise bean through the local interface. It abstracts the business object interactions and provides a service layer. It makes the performance fast over the network.
Some of the key actors in persistence API are :
 
* Entity
* Data source
* EntityManager
* Persistence unit
* Create a stateless EJB
* Update stateless EJBM
* Create a database table
* Create entity classes for the table
* Create persistent unit and data source
* Console based application accesses the stateless EJB.
@javax.ejb.Stateless annotation specifies that a given ejb class is a stateless session bean. Following are its attributes :
 
name  : Used to specify name of the session bean.
mappedName  : Used to specify the JNDI name of the session bean.
description : Used to provide description of the session bean.
@javax.ejb.Stateful annotation specifies that a given ejb class is a stateful session bean. Following are its attributes :

name : Used to specify name of the session bean.
mappedName : Used to specify the JNDI name of the session bean.
description : Used to provide description of the session bean.
When “one to one” mapping is involved, and the data is stored persistently is regional database, CMP is preferred. But when no “one to one” mapping is there and data is retrieved from numerous tables having a complex query, Bean Managed Persistence is used.
When the method is called before the persistence storage is written with the bean state, it is ejbCreate().
 
When the method is called after the persistence storage is written with the bean state, it is ejbPostCreate().
ACID is Atomicity, Consistency, Isolation and Durability.
 
Atomicity : Operations that are bundled together and projected a single unit of job.
Consistency : Guarantees that after a transaction has taken place, there will be consistency.
Isolation : Helps protect viewing of other simultaneous incomplete transaction results.
Durability : Ensures durability by keeping a transitional log by which the permanent data be recreated by again applying the steps involved.
A query language which provides navigation through a network comprising enterprise beans and objects which are dependent and are defined by methods of container managed persistence. EJB 2.0 was the platform for introduction of EJB QL. It defines methods of finder which are used for entity beans, which has container managed persistence and has portability across persistence managers and containers. It is helpful in two kinds of finder methods: Finder methods, which have Home interface and return objects of entity. Select methods, which remain unexposed for the client to see but which the Bean provider uses.
Home Object reference is retrieved from the Naming Service via JNDI. Home Object reference is returned to the client. The steps are :
 
* Created a new EJB Object via Home Object interface.
* Created an EJB Object from the Ejb Object.
* Returned an EJB Object reference to the client.
* Invoked business method by using EJB Object reference.
* Delegate requested to Bean (Enterprise Bean).
Modules are packaged based on their functionality as EAR, JAR and WAR files.
 
JAR files (.jar) : Modules which contain EJB class files and EJB deployment descriptor are packed as JAR files.
WAR Files (.war) : Web modules which contain Servlet class files, JSP Files, supporting files, GIF and HTML files are packaged as JAR file.
EAR Files (.ear) :  ‘.jar’ & ‘.war’ files are packaged as JAR files. ‘Ear’ stands for enterprise archive. These files are deployed in the application server.
The remote client view specification is only available in EJB 2.0. The remote client view of an enterprise bean is location independent. A client running in the same JVM as a bean instance uses the same API to access the bean as a client running in a different JVM on the same or different machine.
 
Remote interface : The remote interface specifies the remote business methods that a client can call on an enterprise bean.
Remote home interface : The remote home interface specifies the methods used by remote clients for locating, creating, and removing instances of enterprise bean classes.
Below are the callback annotations for the stateless bean :
 
@PostConstruct : method is invoked when a bean is created for the first time.
@PreDestroy : When a bean is destroyed or displaced from the bean pool, this method is invoked.
Here are some transaction attributes
 
Required : No new transaction is created when the required attributed is linked to the transaction.
Requires New : There is always present the addition of a new transaction when this attributed is linked to the transaction.
Not Supported : If the method is linked to this attribute then the method does not remain part of the transaction
Supported : It acts in the conditional case that depends on the calling component. If the calling element is linked with transaction then the method act as a required attribute. If the calling component is not linked with the transaction then the method acts as NOT SUPPORTED.
Mandatory : The method is always called from the calling element transaction context when the method is linked to this attribute.
Never : The method is never called from the calling element transaction context when the method is linked to this attribute.

Support is the default transaction value of EJB.
Atomic : In this case, if any working part fails then the whole work is considered as destroyed. It values only fully successful.
Consistent : It represents that the transaction management must remain in a consistent state
Isolated : It states that the execution of the transaction is independent of the other transactions.
Durable : It means if any by case transaction has been executed then it must have survived system failure.
@javax.ejb.MessageDrivenBean annotation specifies that a given ejb class is a message driven bean. Following are its attributes :

name - Used to specify name of the message driven bean.
messageListenerInterface - Used to specify message listener interface for the message driven bean.
activationConfig - Used to specify the configuration details of the message-driven bean in operational environment of the message driven bean.
mappedName - Used to specify the JNDI name of the message driven bean.
description - Used to provide description of the message driven bean.
@javax.ejb.EJB annotation is used to specify or inject a dependency as ejb instance into another ejb. Following are its attributes :

name : Used to specify name which will be used to locate the referenced bean in environment.
beanInterface : Used to specify the interface type of the referenced bean.
beanName : Used to provide name of the referenced bean.
mappedName : Used to specify the JNDI name of the referenced bean.
description : Used to provide description of the referenced bean.
@javax.ejb.Local annotation is used to specify Local interfaces of a session bean. This local interface states the business methods of the session bean whichcanbestatelessorstateful.

This interface is used to expose the business methods to local clients which are running in same deployment/application as EJB.
@javax.ejb.Remote annotation is used to specify Remote interfaces of a session bean. This remote interface states the business methods of the session bean whichcanbestatelessorstateful.
 
This interface is used to expose the business methods to remote clients which are running in different deployment/application as EJB.
@javax.ejb.ActivationConfigProperty annotation is used to specify properties required for a message driven bean. For example end point, destination, message selector etc.

This annotation is passed as a parameter to activationConfig attribute of javax.ejb.MessageDrivenBean annotation. Following are its attributes:

propertyName - name of the property.
propertyValue - value of the property.
@javax.ejb.PostActivate annotation is used to specify callback method of ejb lifecycle. This method will be called when EJB container just activated/reactivated the bean instance. This interface is used to expose the business methods to local clients which are running in same deployment/application as EJB.
EJB 3.0 specification provides annotations which can be applied on fields or setter methods to inject dependencies. EJB Container uses the global JNDI registry to locate the dependency.
Following java types can be mapped using @Lob annotation :

* java.sql.Blob
* java.sql.Clob
* byte[]
* String
* Serializable Object
EJB 3.0 has specified following attributes of transactions which EJB containers implement :

REQUIRED : Indicates that business method has to be executed within transaction otherwise a new transaction will be started for that method.
REQUIRES_NEW : Indicates that a new transaction is to be started for the business method.
SUPPORTS : Indicates that business method will execute as part of transaction.
NOT_SUPPORTED : Indicates that business method should not be executed as part of transaction.
MANDATORY : Indicates that business method will execute as part of transaction otherwise exception will be thrown.
NEVER : Indicates if business method executes as part of transaction then an exception will be thrown.
Because an EJB consists of multiple “parts”, inheritance is achievable in a rather limited fashion (see FAQ answer on inheritance here). There have been noteworthy suggestions on using multiple inheritance of the remote interface to achieve polymorphism, but the problem of how to share method signatures across whole EJBs remains to be addressed. The following is one solution to achieving polymorphism with Session Beans. It has been tried and tested on WebLogic Apps Server 4.50 with no problems so far.

We will use an example to show how it’s done. Say, there are 2 session beans, Tiger and Lion, that share some method signatures but provide different implementations of the methods.

* AnimalBean is the base implementation bean.
* AnimalHome and Animal are the home and remote interfaces. The signatures of the polymorphic methods are in Animal.
* TigerBean and LionBean extend from AnimalBean. They may override the methods of AnimalBean, implementing different behaviors.
* Deploy Tiger and Lion beans, specifying AnimalHome and Animal as their home and remote interfaces. Note that Tiger and Lion should have different JNDI lookup names.
Taken from Enterprise JavaBeans by Richard Monson-Haefel, “EJB, by default, prohibits concurrent access to bean instances. In other words, several clients can be connected to one EJB object, but only one client thread can access the bean instance at a time. If, for example, one of the clients invokes a method on the EJB object, no other client can access that bean instance until the method invocation is complete.” So, to answer your question, two users will never access an Entity Bean concurrently.
A common way to do it is to use a stateless session bean to retrieve the ID that you wish to use as the primary key. This stateless session bean can then execute an Oracle sequencer or procedure etc. to retrieve the ID value used as the primary key.
The passivation of Entity beans is managed by the container. To passivate an instance, the container first invokes the ejbStore() method for synchronizing the database with the bean instance, then the container invokes the ejbPassivate() method. It will then return the bean instance back to the pooled state. (Every bean has an instance pool.) There are two ways for transitioning an entity bean from the ready to the pooled state, by using the ejbPassivate() or ejbRemove() method. The container uses ejbPassivate() to disassociate the bean instance from the entity object identity, and uses ejbRemove() to remove the entity object. When the instance is put back into the pool, it is no longer associated with an entity object identity. The container can now assign the instance to any entity object within the same entity bean home. A bean instance in the pool can be removed by using unsetEntityContext().
The steps that are followed :

*
Home Object Interface creates a new EJB object
* Gives back EJB object reference to the client
* With the use of EJB object reference invokes business methods
* Delegate requests to the bean.
The services that are provided to EJB components by the EJB container are caching, concurrency, environment, memory replication, transaction, naming, persistence support, and clustering for the entity objects that live in the container.
* An applet must use the same procedure as any other Java class: it must use JNDI to locate the EJB Home Interface, then use RMI to talk with the Home Interface as well as the EJB itself.

* This means that the J2EE and/or JNDI and/or RMI classes need to be present in the applet’s Java Virtual Machine. The easiest way to assure this is to use the latest Java Plug-in. Netscape 6, aka Mozilla, ships with the Java Plug-in. Other browsers have various problems with RMI and JNDI classes that are beyond the scope of this answer.

* Note, however, that it is not recommended to use EJB directly from applets, in part due to compatibility issues. Instead, you can use Servlets inside the application server to provide an HTML front-end that is assured to work on a much larger base of clients.
Clustering refers to the ability of multiple load-balanced web servers to share session and entity data. It is a major feature of web application servers. Standardized support for clustering was one of the primary motivations behind the EJB spec.

Clustering also applies to Servlet containers sharing HttpSession data (similar to EJB Session Beans).
@EJB annotation is used to inject other EJB reference.
EJB 3.0 provides specification to intercept business methods calls using methods annotated with @AroundInvoke annotation. An interceptor method is called by ejbContainer before business method call it is intercepting.
Class level interceptor is invoked for every method of the bean. Class level interceptor can be applied both by annotation or via xml(ejb-jar.xml).
In Bean Managed Transactions, Transactions can be managed by handling exceptions at application level. Following are the key points to be considered :
 
Start : When to start a transaction in a business method.
Sucess : Identify success scenario when a transaction is to be committed.
Failed : Identify failure scenario when a transaction is to be rollback.
Any exception which is not caused by business logic or business code. RuntimeException, RemoteException are SystemException. For example, error during ejb lookup.Then EJB container treats such exception as System level exception.
Timer Service is a mechanism using which scheduled application can be build. For example, salary slip generation on 1st of every month. EJB 3.0 specification has specified @Timeout annotation which helps in programming the ejb service in a stateless or message driven bean. EJB Container calls the method which is annotated by @Timeout.
 
EJB Timer Service is a service provided by Ejb container which helps to create timer and to schedule callback when timer expires.