Home  >  Blog  >   Java

What is EJB?

Are you wondering why EJB plays a crucial role in developing and deploying robust Java applications? Do you want to know about software components or Beans in EJB? No worries! You have landed on the right page. This tutorial is an easy guide to learning EJB concepts in greater detail. Here, we have covered the types of EJB, various client-access methods, different life cycles of EJB, and much more. We have added practical examples to learn about creating enterprise beans, packaging them, and so on. Ready to go?

Rating: 4.8
  
 
647
  1. Share:
Java Articles

EJB is an architecture used to distribute program components across multiple clients. It has powerful server-side capabilities with which you can develop and deploy programs across all platforms. In this tutorial, you can learn EJB, its various types, different client access methods, the lifecycles of different EJB, creating EJB, packaging EJB, and mapping EJB with references in greater detail.

Let’s dive into the topics!

EJB Tutorial - Table of Contents

If you want to enrich your career and become a professional in EJB, then enroll in "Core Java Training". This course will help you to achieve excellence in this domain.

What is EJB?

EJB is the short form of Enterprise JavaBeans. It is part of the J2EE platform and built on JavaBeans technology. EJB is a server-side platform that runs based on a server-client model. This platform provides software components to build distributed and robust business applications. The software components are generally written in Java language. EJB architecture includes three components: EJBs, Java application server, and EJB container. Here, the EJB container is nothing but a runtime environment where you can run EJB applications.

EJB Architecture

Mainly, EJB focuses on the business logic of applications. Business logic represents the core functionality of an application. You can use EJB to simplify large-scale business applications. You can also develop and deploy highly scalable and high-performance applications effortlessly.

Why EJB?

Are you wondering why EJB is one of the powerful platforms for developing large-scale Java applications? The following points will help you in this regard:

  • Clients can seamlessly run on small devices when using EJB software components.
  • EJB is portable. So, you can run EJB on any J2EE server.
  • The EJB container provides system-level services. So, you can easily manage transaction management as well as security authorization in EJB applications.
  • EJB helps solve business problems by effectively managing the business logic of applications.
  • EJB is scalable. So, you can seamlessly increase the number of machines to run EJB.
  • EJB ensures data integrity. It allows concurrent access to shared objects.
  • Remote clients can quickly locate EJB.

What are the Types of EJB?

Know that there are three types of EJB as given below:

  1. Session beans
  2. Entity beans
  3. Message-driven beans.

Types of EJB

In the following sections, let's be ready to look at the different types of beans and their features.

1. What are Session Beans?

By using session beans, you can make interactive sessions with clients. The interactive sessions get terminated when the clients leave. Essentially, session beans provide web services and perform tasks for clients.

Stateful beans and stateless beans are the types of session beans. Let's have a brief of them in the following:

  • Stateful Beans: Stateful beans maintain the session information. In other words, they maintain the conversational state, including all transactions between session beans and clients, and multiple calls. Know that every instance of a stateful session bean will have a unique identity. And this identity is assigned by the EJB container at the time of instance creation. In this type, the instance variables represent the state of a session bean.
  • Stateless Beans: Unlike stateful beans, stateless beans don’t maintain the information of sessions. In other words, they don’t maintain a conversational state. All the instances of stateless beans will have a common identifier. In this type, the instances' variables keep the session's state until the end. Once the session is over, the state of the session will no longer continue. It means that when there is no session, the states of all session beans are the same. It allows the EJB container to assign session bean instances to any client without worrying about the state of the instances.

Stateless beans offer good scalability. So, they can support any number of clients. As a result, stateless beans offer better performance than stateful beans. Stateless beans are not written in secondary storage, whereas stateful beans are written in secondary storage. No wonder only a stateless bean can provide web services.

[ Check out Configuring the EJB Components ]

How to Create the Enterprise Bean?

2. What are Entity Beans?

Entity beans represent business entity objects stored in a persistent storage device, such as a relational database. The business entity may be customers, products, orders, etc. Know that entity beans offer many features such as persistence, primary keys, shared access, and relationship with other beans.

Let’s discuss the features below:

  • Persistence: Entity Bean follows persistence. It means that a bean's state is stored even after the lifetime of an application. Entity beans follow two types of persistence. One is bean-managed persistence, and another is container-managed persistence. To use bean-managed persistence, you need to include calls in codes to access databases. Regarding container-managed persistence, you don't need to add calls in codes because EJB containers automatically add calls in codes.
  • Shared Access: Many clients can share entity beans. But they must operate within transactions because clients may change data. In this regard, EJB containers manage the transactions.
  • Primary Key: Know that every entity bean is provided with a unique object identifier. This identifier is nothing but a primary key. A client can quickly locate an entity bean in the application server with a primary key. For example, you can use a customer number as a primary key to locate a customer entity.
  • Relationships: You can relate every entity bean with other entity beans. EJB encourages two types of relationships such as bean-managed relationships as well as container-managed relationships. Codes play a crucial role in bean-managed relationships, and EJB container plays a key role in container-managed relationships.

3. What are Message-driven Beans?

No wonder a single message-driven bean can manage multiple messages from multiple clients. The messages could be JMS messages or any other messages. Here, JMS is nothing but an API that supports communication between various application components. You can use it as a middleware to create, receive, send, and read messages. Also, JMS messages can be sent to application clients, web components, and other Enterprise beans seamlessly. In a way, message-driven beans are similar to stateless beans since both don't hold the state of beans instances at any time. Above all, Message-driven beans help java applications to run asynchronously.

MindMajix Youtube Channel

What are the Different Client-Access Methods Used in EJB with Interfaces?

No doubt that any type of client can access Enterprise Beans invariably. The client may be a remote, web service, or local client. By using interfaces, clients can access entity beans and session beans. On the contrary, message-driven beans cannot be accessed through interfaces. Besides, EJB allows client access using only the methods defined in the interfaces.

Three types of client access methods are used in EJB: remote, web service, and local. You can choose either local or remote access by considering many factors, such as container-managed relationships, the type of coupling between related beans, component distribution, type of clients, and performance.

  • Remote Clients: A remote client could be an application or web component. No surprise, it could be another Enterprise bean. In this type, the location of the Enterprise bean is transparent to the remote client. To access Enterprise beans remotely, you must write codes for the home interface and remote interface. When it comes to remote interface, it defines business methods. At the same time, the home interface defines the bean’s lifecycle methods. Note that lifecycle methods perform the create and remove actions, whereas business methods perform business activities such as credit, deposit, etc.
  • Local Clients: A local client can be a web component or any other Enterprise bean. The same JavaVirtualMachines (JVM) must locate local clients as well as Enterprise Beans. Unlike remote access, the location of an Enterprise bean is not transparent to local clients. However, similar to remote access, you need to write codes for the local interface as well as the local home interface to access Enterprise Beans. Here, the local interface defines the bean’s business methods, whereas the local home interface defines lifecycle methods.
  • Web Service Clients: A web service can access java applications in two ways. One way, a client can access a web service created based on JAX-RPC. Here, JAX-RPC is nothing but an XML-based remote procedure call. In another way, a web service can quickly call a stateless session bean's business methods. Unlike remote and local clients, a web service client doesn't use home interfaces but business methods. And the business methods are defined by the web service endpoint interface.

Client-Access Methods Used in EJB

What are the Life Cycles of Different EJB?

Be it a session, message-driven, or entity Enterprise Bean, they come with different lifecycles. Let’s discuss them below:

1. Life Cycle of a Stateful Session Bean

A client can initiate the lifecycle of a stateful session bean by raising the ‘create’ method. Once instantiated, the EJB container raises the setSessionContext method in the session bean. After that, it raises the ejbCreate method in the bean. Now, the session bean is ready to enable business methods. When the session bean goes to the ready state, the EJB container can activate or passivate the bean. For passivation, the EJB container raises the ejbPassivate method. During the passivation, the bean is moved from memory to secondary storage. When the client raises the business methods, the EJB container enables the bean through the ejbActivate method.

Life Cycle of a Stateful Session Bean

After that, the EJB container moves the bean to a ready state. When the client wants to end the session bean, it performs the remove method. Once done, the EJB container raises the ejbRemove method to terminate the session.

2. Life Cycle of a Stateless Session Bean

There is no passivation stage in the lifecycle of a stateless session bean. Stateless session bean has only two stages. The first stage is known as 'non-existent', and another is known as 'ready'. Generally, the business methods are raised in the ‘ready’ stage.

Life Cycle of a Stateless Session Bean

3. Life Cycle of an Entity Bean

As a first step in the life cycle of an entity bean, the EJB container creates an entity bean’s instance. Then, the EJB container raises the setEntityContext method to transfer the entity context to the bean. After that, the bean moves to the pool of instances. The EJB container creates an identity to the entity bean’s instance while moving it to the ready state.

By using two ways, you can move entity bean from pooled state to ready state. In one way, a client raises the create method, and then the EJB container raises the EJBCreate method. After that, it raises the ejbPostCreate method. In another way, the EJB container raises the ejbActivate method. As you know, when beans are in the ready state, clients can raise business methods.

Life Cycle of an Entity Bean

In reverse, beans can move from a ready state to pooled state in two ways. In one way, a client raises the remove method, and then the EJB container calls the ejbRemove method. In another way, the client raises the ejbPassivate method. At the end of this lifecycle, the EJB container raises the unsetEntityContext method. And then it removes entity bean instances from the pool.

4. Life Cycle of a Message-Driven Bean

This life cycle of a message-driven bean has only two stages. One is the 'non-existent' stage, and another one is 'ready' to receive messages. Similar to the life cycle of a stateless session bean, the life cycle of a message-driven bean is not passivated. In this lifecycle, the EJB container creates a group of message-driven bean instances. Then the EJB container passes the context object to every instance by raising the setMessageDrivenContext method. Then it calls the ejbCreate method. The EJB container raises the ejbRemove method at the end of this lifecycle.

Life Cycle of a Message-Driven Bean

Here, we will learn how to create ConverterBean – an Enterprise Bean. ConverterBean is the application used to convert currencies. Consider that this bean is the stateless session bean. You will need to follow the below two steps to create the ConverterBean.

  • You need to code the bean’s implementation class.
  • You need to compile the source code.

Let's see know how to perform these two steps one by one.

Step 1: Coding the Enterprise Bean Class

ConverterBean is the Enterprise Bean class used in this example. This class supports implementing two business methods: converting YenToEuro and DollerToYen. And this class represents a no-interface and local view since it doesn’t implement a business interface. Besides, clients can use public methods in this class.

The source code for the Enterprise Bean class is given below:

Enterprise Bean Class Code

Step 2: Creating the Converter Web Client

Know that a Java Servlet is nothing but a web component that can respond to HTTPS requests. You can find the web client in the following Servlet class.

Converter/web/ConverterServlet.java

Generally, ConverterServlet class refers to ConverterBean using dependency injection. And javax.ejb.EJB annotation is included when declaring private member variable converter. Enterprise Bean implementation class is the variable type since ConverterBean represents no-interface and a local view. You can understand this from the following codes.

Creating the Converter Web Client

The amount is collected from the request parameters when you enter the amount converted from Yen to Euro or Dollar to Yen. The conversion will be performed by calling methods such as ConverterBean.YenToEuro and ConverterBean.DollarToYen.

Creating the Converter Web Client

Step 3: Running the Converter

You can compile the Servlet class and Enterprise Bean class at this stage. Then, you can package the compiled classes in a WAR file. You can use either Maven or NetBeans IDE for building, packaging, running, and deploying the codes.

If you want to use NetBeans IDE to run the codes, then you can follow the below steps:

  • Initiate GlassFish Server
  • Select ‘Open Project’ from the ‘File’ menu
  • Select the ‘converter’ folder
  • Then, click ‘OpenProject’
  • Right-click the ‘converter’ project in the ‘Projects’ tab
  • Now, select ‘Build’
  • Open the following URL in a web browser http://localhost:8080/converter
  • Open the Servlet ConverterServlet page, then enter the value 100 in the field
  • Now, click ‘Submit’, and you can get the converted values.

How to Package the Enterprise Bean in the EJB JAR File?

To package Enterprise Beans, you need to run the ‘edit Enterprise bean wizard’ of the ‘deploy tool’ utility. When you start this process, the wizard will do the following actions.

  • The wizard creates the ‘deployment descriptor’ of the Enterprise Bean.
  • It packages the classes of the Bean and ‘deployment descriptor’ in an EJB JAR file.
  • Then, the wizard inserts the EJB JAR file into the ConverterApp.ear file.

Let’s understand how the packaging of Enterprise Beans is performed using the steps mentioned above in the following sections.

First of all, start the ‘edit Enterprise Bean wizard’. Then go to ‘file’, select ‘new’, and then choose ‘Enterprise Bean’.

Now, you can see the following dialog boxes will open in the wizard.

Introduction Dialog Box

  • In this dialog Box, you can view the explanatory content about the features of the wizard.
  • Then, click the ‘Next’ button.

EJB JAR Dialog Box

  • In this dialog box, as a first step, click the button for ‘create new JAR Module’
  • Then, choose the ‘ConverterApp’ below the combo box
  • Enter ‘ConverterJAR’ in the JAR Display name field
  • Now, you can click the button for ‘Edit Contents’
  • Identify the build/converter subdirectory in the tree under the available files
  • You can select the classes such as Converter.class, ConverterBean.class, and ConverterHome.class. from the available files tree.
  • Then, click the buttons ‘Add’ and then ‘OK’
  • Finally, click the ‘Next’ button.

General Dialog Box

  • In this general dialog box, at first, you can choose the ‘stateless session’ under the Bean type
  • Then, choose the converter.ConverterBean in the Enterprise Bean Class combo box
  • Enter the ConverterBean in the Enterprise Bean Name field
  • Then, choose the converter.ConverterHome in the Remote Home Interface combo box
  • Choose the converter. Converter in the Remote Interface combo box
  • Click the button for ‘Next’
  • Now, choose ‘No’ in the ‘Expose as Web Service Endpoint’ dialog box
  • Finally, click the ‘Next’ and ‘Finish’ buttons.

How to Map the Enterprise Bean References?

Whether you use a web client or an application client to access the same Enterprise Bean, you must use different names in codes to refer to the beans. Simply put, the application client refers to bean’s home as ejb/SimpleConverter, whereas the web client refers to bean’s home as ejb/TheConverter. If only you map the references in codes to the JNDI name of the Enterprise Beans, you can use the lookup method to retrieve the home bean.

You can follow the below steps to map the references in codes to the JNDI names.

  • At first, choose the ConvertApp in the tree
  • Click the button for ‘sun-specific settings’
  • In the view field, choose the JDNI names
  • Now, you can see in the application table that ConverterBean is the JDNI name for the Enterprise bean
  • Then, enter ConverterBean in the JNDI name column for every row in the reference's table.
Learn EJB Interview Questions and Answers that help you grab the high-paying jobs

What are the Advantages of EJB?

There are a lot of advantages when clients use the EJB platform for developing and deploying java applications. Let’s have a look at them below:

  • EJB containers provide system-level services and manage EJB lifecycles effectively.
  • EJB architecture is compatible with other APIs such as JSPs and Servlets
  • EJB focuses on business logic. That’s why it quickly solves complex business problems and builds large-scale applications
  • EJB instances can be easily pooled
  • Applications built on EJB are capable of running on Java web application servers
  • EJB components are portable.

What are the Limitations of EJB?

Undeniably, there are a few limitations that exist for EJB. Let’s take a look at them below:

  • EJB specification is complex and large
  • EJB requires an application server
  • Only Java clients can use EJB
  • Development time is a bit longer while using EJB
  • EJB releases continuous revisions.

Conclusion

In a nutshell, EJB is the platform for providing software components (beans) to develop distributed and large-scale enterprise applications. EJB functions based on the business logic of an application, which in turn supports building robust java applications. By offering system-level services, EJB ensures effective transaction management and security aspects in the EJB applications. This tutorial covered the different types, various client access methods, and lifecycles of enterprise beans. The practical examples on how to create, package, and map enterprise beans might have helped to learn the EJB concepts in a detailed way.

Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
Core Java TrainingApr 30 to May 15View Details
Core Java TrainingMay 04 to May 19View Details
Core Java TrainingMay 07 to May 22View Details
Core Java TrainingMay 11 to May 26View Details
Last updated: 04 Apr 2023
About Author

 

Madhuri is a Senior Content Creator at MindMajix. She has written about a range of different topics on various technologies, which include, Splunk, Tensorflow, Selenium, and CEH. She spends most of her time researching on technology, and startups. Connect with her via LinkedIn and Twitter .

read more
Recommended Courses

1 / 15