EJB Tutorial
EJB Tutorial
EJB (Enterprise Java Bean) is used to develop scalable, robust and secured enterprise applications in
java.
Unlike RMI, middleware services such as security, transaction management etc. are provided by EJB
Container to all EJB applications.
The current version of EJB is EJB 3.2. The development of EJB 3 is faster than EJB 2 because of
simplicity and annotations such as @EJB, @Stateless, @Stateful, @ModelDriven, @PreDestroy,
@PostConstruct etc.
PlayNext
Mute
Duration 18:10
Loaded: 0.37%
Fullscreen
What is EJB
What is enterprise java beans(EJB) and what are the advantages of EJB?
Session Bean
The session bean represents the business logic. It may be stateless, stateful or singleton.
JMS Tutorial
How to create robust and asynchronous message for distributed applications. What are messaging
domains?
What is Java Messsage Service and what are the advantages of JMS.
What is JMS Queue? It is used for peer to peer messaging where a single message is delivered to only
one receiver.
What is JMS Topic? It is also known as Publisher and Subscriber model where a single message is
delivered to all the subscribers.
A MDB is a JMS client that is invoked by passing message. It is deployed on the application server.
Entity Bean
What is EJB
EJB is an acronym for enterprise java bean. It is a specification provided by Sun Microsystems to
develop secured, robust and scalable distributed applications.
To run EJB application, you need an application server (EJB Container) such as Jboss, Glassfish,
Weblogic, Websphere etc. It performs:
b. security,
d. object pooling.
EJB application is deployed on the server, so it is called server side component also.
EJB is like COM (Component Object Model) provided by Microsoft. But, it is different from Java Bean,
RMI and Web Services.
2. Application needs to be scalable. EJB applications supports load balancing, clustering and
fail-over.
Session Bean
Session bean contains business logic that can be invoked by local, remote or webservice client.
Message Driven Bean
Like Session Bean, it contains the business logic but it is invoked by passing message.
Entity Bean
It encapsulates the state that can be persisted in the database. It is deprecated. Now, it is replaced
with JPA (Java Persistent API).
Both RMI and EJB, provides services to access an object running in another JVM (known as remote
object) from another JVM. The differences between RMI and EJB are given below:
RMI EJB
RMI is not a server-side component. It is not required to be EJB is a server-side component, it is required to be
deployed on the server. deployed on the server.
RMI is built on the top of socket programming. EJB technology is built on the top of RMI.
In EJB, bean component and bean client both must be written in java language.
If bean client need to be written in other language such as .net, php etc, we need to go
with webservices (SOAP or REST). So EJB with web service will be better option.
Disadvantages of EJB
2. Requires only java client. For other language client, you need to go for webservice.
4. Session Bean
5. Session bean encapsulates business logic only, it can be invoked by
local, remote and webservice client.
6. It can be used for calculations, database access etc.
7. The life cycle of session bean is maintained by the application server
(EJB Container).
8. Types of Session Bean
9. There are 3 types of session bean.
10. 1) Stateless Session Bean: It doesn't maintain state of a client
between multiple method calls.
11. 2) Stateful Session Bean: It maintains state of a client across
multiple requests.
12. 3) Singleton Session Bean: One instance per application, it is
shared between clients and supports concurrent access.
Stateless Session bean is a business object that represents business logic only. It doesn't have state
(data).
In other words, conversational state between multiple method calls is not maintained by the
container in case of stateless session bean.
The stateless bean objects are pooled by the EJB container to service the request on demand.
It can be accessed by one client at a time. In case of concurrent access, EJB container routes each
request to different instance.
2. @PostConstruct
3. @PreDestroy
There is only two states of stateless session bean: does not exist and ready. It is explained by the
figure given below.
EJB Container creates and maintains a pool of session bean first. It injects the dependency if then
calls the @PostConstruct method if any. Now actual business logic method is invoked by the client.
Then, container calls @PreDestory method if any. Now bean is ready for garbage collection.
To develop stateless bean application, we are going to use Eclipse IDE and glassfish 3 server.
To create EJB application, you need to create bean component and bean client.
To create the stateless bean component, you need to create a remote interface and a bean class.
File: AdderImplRemote.java
1. package com.javatpoint;
2. import javax.ejb.Remote;
3.
4. @Remote
5. public interface AdderImplRemote {
7. }
File: AdderImpl.java
1. package com.javatpoint;
2. import javax.ejb.Stateless;
3.
4. @Stateless(mappedName="st1")
7. return a+b;
8. }
9. }
The stateless bean client may be local, remote or webservice client. Here, we are going to create
remote client. It is console based application. Here, we are not using dependency injection. The
dependency injection can be used with web based client only.
File: AdderImpl.java
1. package com.javatpoint;
2. import javax.naming.Context;
3. import javax.naming.InitialContext;
4.
8. AdderImplRemote remote=(AdderImplRemote)context.lookup("st1");
9. System.out.println(remote.add(32,32));
10. }
11. }
Output
Output: 64
Stateful Session Bean
Stateful Session bean is a business object that represents business logic like stateless session bean.
But, it maintains state (data).
In other words, conversational state between multiple method calls is maintained by the container in
stateful session bean.
1. @Stateful
2. @PostConstruct
3. @PreDestroy
4. @PrePassivate
5. @PostActivate
To develop stateful session bean application, we are going to use Eclipse IDE and glassfish 3 server.
As described in the previous example, you need to create bean component and bean client for
creating session bean application.
Let's create a remote interface and a bean class for developing stateful bean component.
File: BankRemote.java
1. package com.javatpoint;
2. import javax.ejb.Remote;
3. @Remote
7. int getBalance();
8. }
File: Bank.java
1. package com.javatpoint;
2. import javax.ejb.Stateful;
3. @Stateful(mappedName = "stateful123")
7. if(amount<=this.amount){
8. this.amount-=amount;
9. return true;
10. }else{
12. }
13. }
15. this.amount+=amount;
16. }
19. }
20. }
The stateful bean client may be local, remote or webservice client. Here, we are going to create web
based client and not using dependency injection.
File: index.jsp
File: operation.jsp
1. <form action="operationprocess.jsp">
3.
4. Choose Operation:
8. <br>
10. </form>
File: operationprocess.jsp
2. <%
3. BankRemote remote=(BankRemote)session.getAttribute("remote");
4. String operation=request.getParameter("operation");
5. String amount=request.getParameter("amount");
6.
7. if(operation!=null){
8.
9. if(operation.equals("deposit")){
10. remote.deposit(Integer.parseInt(amount));
12. }else
13. if(operation.equals("withdraw")){
15. if(status){
17. }else{
19. }
20. }else{
22. }
23. }
24. %>
25. <hr/>
1. package com.javatpoint;
2. import java.io.IOException;
3. import javax.ejb.EJB;
4. import javax.naming.InitialContext;
5. import javax.servlet.ServletException;
6. import javax.servlet.annotation.WebServlet;
7. import javax.servlet.http.HttpServlet;
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10. @WebServlet("/OpenAccount")
12. //@EJB(mappedName="stateful123")
13. //BankRemote b;
16. try{
19.
20. request.getSession().setAttribute("remote",b);
22.
24. }
25. }
JMS Tutorial
JMS (Java Message Service) is an API that provides the facility to create, send and read messages. It
provides loosely coupled, reliable and asynchronous communication.
JMS is mainly used to send and receive message from one application to another.
Requirement of JMS
Generally, user sends message to application. But, if we want to send message from one application
to another, we need to use JMS API.
Consider a scenario, one application A is running in INDIA and another application B is running in
USA. To send message from A application to B, we need to use JMS.
Advantage of JMS
1) Asynchronous: To receive the message, client is not required to send request. Message will arrive
automatically to the client.
Messaging Domains
In PTP model, one message is delivered to one receiver only. Here, Queue is used as a message
oriented middleware (MOM).
In Pub/Sub model, one message is delivered to all the subscribers. It is like broadcasting.
Here, Topic is used as a message oriented middleware that is responsible to hold and deliver
messages.
In PTP model, there is timing dependency between publisher and subscriber.
To develop JMS queue example, you need to install any application server. Here, we are
using glassfish3 server where we are creating two JNDI.
After creating JNDI, create server and receiver application. You need to run server and receiver in
different console. Here, we are using eclipse IDE, it is opened in different console by default.
Click on the JMS Resource -> Connection Factories -> New, now write the pool name and select the
Resource Type as QueueConnectionFactory then click on ok button.
Click on the JMS Resource -> Destination Resources -> New, now write the JNDI name and physical
destination name then click on ok button.
2) Create sender and receiver application
Let's see the Sender and Receiver code. Note that Receiver is attached with listener which will be
invoked when user sends message.
File: MySender.java
1. import java.io.BufferedReader;
2. import java.io.InputStreamReader;
3. import javax.naming.*;
4. import javax.jms.*;
5.
8. try
22.
25. while(true)
26. {
29. if (s.equals("end"))
30. break;
31. msg.setText(s);
33. sender.send(msg);
35. }
37. con.close();
39. }
40. }
File: MyReceiver.java
1. import javax.jms.*;
2. import javax.naming.InitialContext;
3.
6. try{
9. QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnecti
onFactory");
11. con.start();
18.
21.
23. receiver.setMessageListener(listener);
24.
27. while(true){
28. Thread.sleep(1000);
29. }
31. }
32.
33. }
File: MyListener.java
1. import javax.jms.*;
3.
5. try{
6. TextMessage msg=(TextMessage)m;
7.
9. }catch(JMSException e){System.out.println(e);}
10. }
11. }
It is same as JMS Queue, but you need to change Queue to Topic, Sender to Publisher and Receiver
to Subscriber.
File: MySender.java
1. import java.io.BufferedReader;
2. import java.io.InputStreamReader;
3. import javax.naming.*;
4. import javax.jms.*;
5.
8. try
13. con.start();
22.
25. while(true)
26. {
29. if (s.equals("end"))
30. break;
31. msg.setText(s);
33. publisher.publish(msg);
35. }
37. con.close();
39. }
40. }
File: MyReceiver.java
1. import javax.jms.*;
2. import javax.naming.InitialContext;
3.
6. try {
9. TopicConnectionFactory f=(TopicConnectionFactory)ctx.lookup("myTopicConnectionFa
ctory");
11. con.start();
18.
21.
23. receiver.setMessageListener(listener);
24.
27. while(true){
28. Thread.sleep(1000);
29. }
31. }
32.
33. }
File: MyListener.java
1. import javax.jms.*;
3.
5. try{
6. TextMessage msg=(TextMessage)m;
7.
9. }catch(JMSException e){System.out.println(e);}
10. }
11. }
Stateless Session bean is a business object that represents business logic only. It doesn't have state
(data).
In other words, conversational state between multiple method calls is not maintained by the
container in case of stateless session bean.
The stateless bean objects are pooled by the EJB container to service the request on demand.
It can be accessed by one client at a time. In case of concurrent access, EJB container routes each
request to different instance.
1. @Stateless
2. @PostConstruct
3. @PreDestroy
There is only two states of stateless session bean: does not exist and ready. It is explained by the
figure given below.
EJB Container creates and maintains a pool of session bean first. It injects the dependency if then
calls the @PostConstruct method if any. Now actual business logic method is invoked by the client.
Then, container calls @PreDestory method if any. Now bean is ready for garbage collection.
To develop stateless bean application, we are going to use Eclipse IDE and glassfish 3 server.
To create EJB application, you need to create bean component and bean client.
To create the stateless bean component, you need to create a remote interface and a bean class.
File: AdderImplRemote.java
1. package com.javatpoint;
2. import javax.ejb.Remote;
3.
4. @Remote
7. }
File: AdderImpl.java
1. package com.javatpoint;
2. import javax.ejb.Stateless;
3.
4. @Stateless(mappedName="st1")
7. return a+b;
8. }
9. }
The stateless bean client may be local, remote or webservice client. Here, we are going to create
remote client. It is console based application. Here, we are not using dependency injection. The
dependency injection can be used with web based client only.
File: AdderImpl.java
1. package com.javatpoint;
2. import javax.naming.Context;
3. import javax.naming.InitialContext;
4.
8. AdderImplRemote remote=(AdderImplRemote)context.lookup("st1");
9. System.out.println(remote.add(32,32));
10. }
11. }
Output
Output: 64
Stateful Session bean is a business object that represents business logic like stateless session bean.
But, it maintains state (data).
In other words, conversational state between multiple method calls is maintained by the container in
stateful session bean.
1. @Stateful
2. @PostConstruct
3. @PreDestroy
4. @PrePassivate
5. @PostActivate
To develop stateful session bean application, we are going to use Eclipse IDE and glassfish 3 server.
As described in the previous example, you need to create bean component and bean client for
creating session bean application.
Let's create a remote interface and a bean class for developing stateful bean component.
File: BankRemote.java
1. package com.javatpoint;
2. import javax.ejb.Remote;
3. @Remote
7. int getBalance();
8. }
File: Bank.java
1. package com.javatpoint;
2. import javax.ejb.Stateful;
3. @Stateful(mappedName = "stateful123")
7. if(amount<=this.amount){
8. this.amount-=amount;
9. return true;
10. }else{
12. }
13. }
15. this.amount+=amount;
16. }
19. }
20. }
The stateful bean client may be local, remote or webservice client. Here, we are going to create web
based client and not using dependency injection.
File: index.jsp
File: operation.jsp
1. <form action="operationprocess.jsp">
3.
4. Choose Operation:
8. <br>
10. </form>
File: operationprocess.jsp
3. BankRemote remote=(BankRemote)session.getAttribute("remote");
4. String operation=request.getParameter("operation");
5. String amount=request.getParameter("amount");
6.
7. if(operation!=null){
8.
9. if(operation.equals("deposit")){
10. remote.deposit(Integer.parseInt(amount));
12. }else
13. if(operation.equals("withdraw")){
15. if(status){
17. }else{
19. }
20. }else{
22. }
23. }
24. %>
25. <hr/>
File: OpenAccount.java
1. package com.javatpoint;
2. import java.io.IOException;
3. import javax.ejb.EJB;
4. import javax.naming.InitialContext;
5. import javax.servlet.ServletException;
6. import javax.servlet.annotation.WebServlet;
7. import javax.servlet.http.HttpServlet;
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10. @WebServlet("/OpenAccount")
12. //@EJB(mappedName="stateful123")
13. //BankRemote b;
16. try{
19.
20. request.getSession().setAttribute("remote",b);
22.
24. }
25. }
JMS Tutorial
JMS (Java Message Service) is an API that provides the facility to create, send and read messages. It
provides loosely coupled, reliable and asynchronous communication.
Understanding Messaging
JMS is mainly used to send and receive message from one application to another.
Requirement of JMS
Generally, user sends message to application. But, if we want to send message from one application
to another, we need to use JMS API.
Consider a scenario, one application A is running in INDIA and another application B is running in
USA. To send message from A application to B, we need to use JMS.
Advantage of JMS
1) Asynchronous: To receive the message, client is not required to send request. Message will arrive
automatically to the client.
Messaging Domains
In PTP model, one message is delivered to one receiver only. Here, Queue is used as a message
oriented middleware (MOM).
In Pub/Sub model, one message is delivered to all the subscribers. It is like broadcasting.
Here, Topic is used as a message oriented middleware that is responsible to hold and deliver
messages.
To develop JMS queue example, you need to install any application server. Here, we are
using glassfish3 server where we are creating two JNDI.
After creating JNDI, create server and receiver application. You need to run server and receiver in
different console. Here, we are using eclipse IDE, it is opened in different console by default.
Click on the JMS Resource -> Destination Resources -> New, now write the JNDI name and physical
destination name then click on ok button.
2) Create sender and receiver application
Let's see the Sender and Receiver code. Note that Receiver is attached with listener which will be
invoked when user sends message.
File: MySender.java
1. import java.io.BufferedReader;
2. import java.io.InputStreamReader;
3. import javax.naming.*;
4. import javax.jms.*;
5.
8. try
22.
25. while(true)
26. {
29. if (s.equals("end"))
30. break;
31. msg.setText(s);
33. sender.send(msg);
35. }
37. con.close();
39. }
40. }
File: MyReceiver.java
1. import javax.jms.*;
2. import javax.naming.InitialContext;
3.
6. try{
9. QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnecti
onFactory");
11. con.start();
18.
21.
23. receiver.setMessageListener(listener);
24.
27. while(true){
28. Thread.sleep(1000);
29. }
31. }
32.
33. }
File: MyListener.java
1. import javax.jms.*;
3.
5. try{
6. TextMessage msg=(TextMessage)m;
7.
9. }catch(JMSException e){System.out.println(e);}
10. }
11. }
It is same as JMS Queue, but you need to change Queue to Topic, Sender to Publisher and Receiver
to Subscriber.
File: MySender.java
1. import java.io.BufferedReader;
2. import java.io.InputStreamReader;
3. import javax.naming.*;
4. import javax.jms.*;
5.
8. try
13. con.start();
22.
25. while(true)
26. {
29. if (s.equals("end"))
30. break;
31. msg.setText(s);
33. publisher.publish(msg);
35. }
37. con.close();
39. }
40. }
File: MyReceiver.java
1. import javax.jms.*;
2. import javax.naming.InitialContext;
3.
6. try {
9. TopicConnectionFactory f=(TopicConnectionFactory)ctx.lookup("myTopicConnectionFa
ctory");
11. con.start();
18.
21.
23. receiver.setMessageListener(listener);
24.
27. while(true){
28. Thread.sleep(1000);
29. }
31. }
32.
33. }
File: MyListener.java
1. import javax.jms.*;
3.
5. try{
6. TextMessage msg=(TextMessage)m;
7.
9. }catch(JMSException e){System.out.println(e);}
10. }
11. }
A message driven bean (MDB) is a bean that contains business logic. But, it is invoked by passing the
message. So, it is like JMS Receiver.
A message driven bean receives message from queue or topic, so you must have the knowledge of
JMS API.
A message driven bean is like stateless session bean that encapsulates the business logic and doesn't
maintain state.
To create the message driven bean, you need to declare @MessageDriven annotation and
implement MessageListener interface.
In eclipse ide, create EJB Project then create a class as given below:
File: MyListener.java
1. package com.javatpoint;
2. import javax.ejb.MessageDriven;
3. import javax.jms.*;
4.
5. @MessageDriven(mappedName="myTopic")
7. @Override
9. TextMessage m=(TextMessage)msg;
10. try{
13. }
14. }
In glassfish server, click on applications -> deploy -> select mdb jar file by Choose File -> OK.
Now send the message using JMS that is covered in the previous page.
Entity Bean in EJB 3.x
Entity bean represents the persistent data stored in the database. It is a server-side component.
In EJB 2.x, there was two types of entity beans: bean managed persistence (BMP) and container
managed persistence (CMP).
Since EJB 3.x, it is deprecated and replaced by JPA (Java Persistence API) that is covered in the
hibernate tutorial.
In hibernate tutorial, there are given hibernate with annotation examples where we are using JPA
annotations. The JPA with Hibernate is widely used today.
Java beans incorporate a set of objects into one accessible object that can be accessed easily from
any application. This single accessible object is maintainable, customizable, and reusable. The
setter/getter method and the single public constructor are used to govern that single accessible
object. We can update and read the value of any variable of any object by using the setter and getter,
respectively.
The EJB stands for Enterprise Java beans that is a server-based architecture that follows the
specifications and requirements of the enterprise environment. EJB is conceptually based on the Java
RMI(Remote Method Invocation) specification. In EJB, the beans are run in a container having four-
tier architecture. This architecture consists of four layers, i.e., Client layer, Web layer, Application
layer, and Data layer.
Architecture
The EJB architecture has two main layers, i.e., Application Server and EJB Container, based on which
the EJB architecture exist. The graphical representation of the EJB architecture is given below.
In the above diagram, the logical representation of how EJBs are invoked and deployed by using
RMI(Remote Method Invocation) is defined. The containers of the EJB cannot be self-deployed. In
order to deploy the containers, it requires the Application server.
Application Server
In the EJB architecture, the Application server is the outermost layer that holds or contains the
Container to be deployed. The application layer plays an important role in executing the application
developed using the beans. It provides the necessary environment to execute those applications.
Some most popular application servers are Web-logic, Tomcat, JBoss, Web-sphere, Wildfly, and Glass-
finish. The main tasks of the application server are:
1. Manage Interfaces
Container
In EJB architecture, the Container is the second outermost layer. It is a very important layer for
enterprise beans that are contained in it. For the enterprise bean, the Container provides various
supporting services, which are as follows:
o It provides support for transactional services such as registering the objects, assign remote
interfaces, purge the instances.
o It provides support for monitoring the object's activities and coordinating distributed
components.
o It provides support for managing the Life-cycle of beans and their concurrency.
Java beans of the enterprise are installed in the Container in the same way as a Plain old java object
(POJO) is installed and registered to the Container. For developing secured, large scale and robust
business applications, beans provide business logic.
Types of EJB
There are three types of Enterprise Java Beans or EJB available, which are as follows:
Stateless EJB
In order to implement the stateless business logic, the stateless EJBs are primarily used. Storing a
user's physical address into an inventory system's database is an example of the stateless EJB. In
addition, a stateless bean would be perfect for this type of business logic because it is not necessary
to have more than two forms on the user interface at all stages of the transaction.
StatelessBeanExample.java
1. package com.javatpoint.ejbarchitecture;
2. import javax.ejb.Stateless;
3.
4. @Stateless
6. }
Stateful EJB
The Stateful EJB is just opposite to the Stateless EJB. The Stateful EJBs are used when we have to
maintain the state of the application on the backend during the user session. The shopping cart of an
online shopping application is an example of the Stateful EJB. In order to achieve such application,
we will use the following steps:
2. After that, for temporarily storing the selected products that are within the user session on
the backend, we have to create a global variable collection of type products.
3. Next, we will create a method through which we will add all the selected products to the
collection that we create in the previous step.
4. We also create a method through which we will remove the product from the collection.
5. In the end, we will create a checkout method for the selected products to process.
StatelessBeanExample.java
1. package com.javatpoint.ejbarchitecture;
2. import javax.ejb.Stateful;
3.
4. @Stateful
6. }
Message-driven EJB
Another special type of EJB that is used for sending and receiving messages from message brokers
implements the JMS specification. The systems based on the broker are loosely coupled. The
components that communicate through the broker have the advantage of not waiting for one
request to finish before submitting another request because the broker by nature is asynchronous.
MessageDrivenBeanExample.java
1. package com.javatpoint.ejbarchitecture;
2. import javax.ejb.MessageDriven;
3. import javax.jms.MessageListener;
4. import javax.jms.Message;
5. import javax.ejb.ActivationConfigProperty;
6.
10. })
12.
14. }
17. }
18. }
S.No. EJB JB
Types of EJB
EJB is an acronym for Enterprise Java Beans. It is a server-side software element. It encapsulates the
business logic of an application. It is a specification for developing a distributed business application
on the Java platform. There are three types of EJBs: Session Bean, Entity Bean, and Message-Driven
Bean. In this section, we will discuss all types of EJB in detail.
Let's discuss one by one in detail.
Session Bean
The bean sprout business idea that can be systematically used by customer, remote, and web service.
When a client wants to use an application distributed on a server, then the client uses session bean
methods. This session bean provides services to customers, protecting them from complex problems
by performing business operations within the server.
To get to an application that is conveyed to the worker, the client summons the meeting bean's
strategies. The meeting bean performs work for its client, safeguarding it from intricacy by executing
business errands inside the worker. Remember that session beans are not persistence.
A stateless session bean doesn't keep a conversational state with the customer or client. When a
client invokes the methods for a stateless bean, the bean's instance variable may contain a state
explicitly to that client however only for the span of the invocation.
At the point when the method has finished, the client explicit state should not be held. However, the
client may change the state of instance variable presented in pooled stateless beans, and this state is
held over to the following invocation of the pooled stateless bean.
Besides this, during the invocation of the method, all instances of a stateless bean are the same,
permitting the EJB container to assign an instance to any client. Therefore, the state of a stateless
session bean should apply across all clients. It can be implemented in a web-services.
Since they can maintain various customers, stateless session beans can offer better adaptability for
applications that require large numbers of clients. Ordinarily, an application requires fewer stateless
session beans than stateful session beans to support the same number of clients.
To improve execution, we may choose a stateless session bean in the event that it has any of these
characteristics.
Advertisement
o The state of the bean has no information or data for a particular client.
o In a private method invocation, the bean performs a generic task for all clients.
A stateful session bean is the same as an interactive session. The state of an object comprises the
values of its instance variables. In a stateful session bean, the instance variables denote the state of a
unique client/bean session. Since, the client interacts with its bean. The state is usually called
the conversational state. It maintains the state of a client across multiple requests. So, we cannot
implement it in the web services because it cannot be shared. When the client terminates the
session, it is no longer associated with the client.
The state is held for the span of the client/bean session. In case if the client eliminates the bean, the
session closes and the state is omitted. This transient nature of the state isn't an issue, because the
interaction between the client and the beans ends. So, it is not required to hold the state.
Stateful session beans should be used, if any of the following conditions are valid:
o The bean's state denotes the alliance between the bean and a particular client.
o The bean needs to hold data about the customer across method invocations.
o The bean interferes between the customer and different segments of the application,
introducing an improved visible to the client.
o In the background, the bean deals with the workstream of a few enterprise beans.
Note: Stateless and stateful both session beans are not persistent.
A singleton session bean maintains one instance per application and the instance exists for the
lifecycle of the application. It offers the same functionality as the stateless session beans. But the
only difference is that there is only one singleton session bean per application while in the stateless
session bean a pool of beans is used.
From that pool, any of the session beans may respond to the client. We can implement it in the web-
service endpoints. It takes care of the state but does not hold the state if unexpected crashes or
shutdown occur. It can be used if we want to perform cleanup tasks on closing the application or shut
down as well. It is because it operates throughout the life cycle of the application.
Singleton session beans are suitable for the following conditions:
o The application needs an enterprise bean to perform undertakings upon application startup
and shutdown.
Entity Bean
Advertisement
It is a far-off object that oversees steady information, performs complex business rationale, possibly
utilizes a few ward Java protests, and can be remarkably distinguished by an essential key. It
ordinarily coarse-grained determined items since they use steady information put away inside a few
fine-grained relentless Java objects. Element beans are diligent on the grounds that they do endure a
worker crash or an organization's disappointment.
Every entity bean has a persistence identity that is associated with it. It means that it comprises a
unique identity that can be fetched if we have a primary key. The type for the unique key is defined
by the bean provider. A client can retrieve the entity bean if the primary has been misplaced. If the
bean is not available, the EJB container first, instantiates the bean and then re-populates the data for
the client.
The diligence for entity bean information is given both to saving state when the bean is passivated
and for improving the state when a failover has detected. It can endure in light of the fact that the
information is put away determinedly by the holder in some type of information stockpiling
framework, like a data set.
Advertisement
Entity beans persist business data by using the following two methods:
It can be used as an alternative to CMP. If the deployment tools are incompatible for mapping the
bean instance's state to the database. The disadvantage of BMP is that more work is required to
define the bean and it ties the bean to a specific database type and structure.
Container-Managed Persistence
In container-managed persistence, the EJB container transparently and implicitly handles the
relationship between the bean and the database. Bean developers focus on the data and the
business process. The principal constraint is that the EJB compartment can most likely not produce
information base access articulations with the proficiency of a programmer.
Unlike BMP, CMP does not allow us to write database access calls in the methods of the entity bean
class. It is because the persistence is handled by the container at run-time. The following two things
are required to support the CMP:
o Runtime Environment: A CMP runtime environment that uses the mapping information to
perform persistence operations on each bean.
Note: Entity bean has been replaced with Java persistence API.
MDB is a Java Messaging Service (message listener). It consumes messages from a queue or
subscription of a topic. It provides an easy way to create or implement asynchronous communication
using a JMS message listener. An advantage of using MDB is that it allows us to use the asynchronous
nature of a JMS listener. We can implement message-driven beans with Oracle JMS (Java Messaging
Service).
There is an EJB container (contains MDBs pool) that handles the JMS queue and topic. Each incoming
message is handled by a bean that is invoked by the container. Note that no object invokes an MDB
directly. All invocation for MDB originates from the container. When the container invokes the MDB,
it can invoke other EJBs or Java objects to continue the request.
It is quite similar to stateless session bean. Because it does not save informal state, also used to
handle multiple incoming requests. EJB has the following benefits over the JMS are as follows:
o It creates a consumer for the listener. It means that the container
creates QueueReceiver or TopicSubscriber is created by the container.
o MDB is registered with the consumer. It means that at deployment time QueueReceiver,
TopicSubscriber, and its factory are registered by the container.
Advertisement
The primary function of MDB is to read (receive) or write (send) incoming from a JMS destination
(i.e. queue or topic). While using MDB ensure that it is configured and installed properly. It interacts
with JMS and the JMS installed on the Oracle database. The database retains queue or topic. The
following figure depicts how MDB interacts with the JMS destination.
o MDB creates and opens a JMS connection to the database by using the data source (JMS
resource provider). The JDBC driver is used to facilitate the JMS connection.
o If any message for the MDB is routed to the onMessage() method of the MDB from the
queue o topic. Other clients may also access the same queue and topic to put the message
for the MDB.
Note that it does not handle the requests that are requested by the clients instead it handles
requests that are placed into a queue.
Method Description
The container dequeues a message from the JMS queu
associated with this MDB and gives it to this instance b
onMessage(msg)
invoking this method. This method must have an
implementation for handling the message appropriate
The following table depicts the key differences between session bean and entity bean.
Persistence of Data It persists data only for the span of the Persistence beyond the life of a cl
conversation with the client. instance. Persistence can be conta
managed or bean-managed.
EJB Container
EJB container is a server-side component that comprises the business logic. It offers local and remote
access to the enterprise beans. In other words, we can say that it provides a runtime environment for
EJB applications within the application server. A single EJB container can have one or more EJB
modules. It acts as an intermediate action between business logic and enterprise application. The
following figure depicts the structure of the EJB container.
The typical behavior envisioned by the Java EE specification is that a developer writes an Enterprise
JavaBean, a simple component, and the EJB container adds the necessary infrastructure for
communications, transactions, and data access. It turns the business logic into something that
executes.
In addition, the EJB container provides lifecycle management for the component to ensure that its
creation, usage, and destruction are both efficient and in accord with the specification.
When the EJB container is started, it has, at its highest level, the EJBContainerImpl class as its
controller. It is a subclass of the generic ContainerImpl class. EJBContainerImpl implements the
EJBContainer service interface and has listeners for changes to the deployed application modules and
other parts of the environment.
Let's see the inheritance dependencies, methods, and interfaces that define the EJB container.
But if we look at the WsComponent interface, we can see some key methods that explain how the
components, and therefore the container, are controlled by the WAS runtime environment. The
ContainerImpl class is a subclass of the ComponentImpl class, so it can be treated like any other
component by the loadComponents calls of the outer container that initializes it. It is how the base
server starts, controls, and interacts with the EJB container.
It is responsible for creating the enterprise bean, binding the enterprise bean to the naming service
so that other application components can access the enterprise bean, ensuring only authorized
clients have access to the enterprise bean's methods, saving the bean's state to persistent storage,
caching the state of the bean, and activating or passivating the bean when necessary.
The EJBContainerImpl class is a complex class with many dependencies, as shown in the following
figure. Some of the dependencies are structural and inheritance-related, and some are dynamic and
collaborative in nature.
Using reflection, we can see the interfaces that the EJBContainerImpl class uses.
Advertisement
o Manage Transactions
o Handles Security
EJB Container provides the following valuable services for enterprise application development.
o Security Model
o Persistence Support
o Messaging
o Remote Access
o Distribution
o Web-services
o Component Pooling
o Component Life-cycle
o Interceptors
o Asynchronous Interactions
There is given EJB interview questions and answers that have been asked in many companies. Let's see the list of top E
interview questions.
1) What is EJB?
EJB stands for Enterprise Java Bean. It is a server-side component to develop scalable, robust and secured enterprise
applications in java. More details...
1. Session Bean
3. Entity Bean
More details...
Session Bean encapsulates business logic. It can be invoked by local, remote or web service client.
More details...
A Stateless session bean is a business object that doesn't maintain the conversational state with the client. More deta
o In case the EJB client environment is the same, use @Local annotation.
A Stateful session bean is a business object that maintains the conversational state with the client. More details...
Singleton session bean is instantiated only once for the application. It exists for the life cycle of the application.
8) What is JMS?
Java Message Service is a messaging service to create, send and receive messages asynchronously. More details...
o Asynchronous
o Reliable
More details...
In Point to Point model, one message is delivered to one receiver only. Here, Queue is used as a message-oriented
middleware. More details...
In the Publisher/Subscriber model, one message is delivered to all subscribers. Here, Topic is used as a message-orient
middleware. More details...
Message Driven Bean (MDB) encapsulates business logic. It is invoked by passing the message. It is like JMS receiver. M
details...
Entity Bean is a server-side component that represents the persistent data. Since EJB 3.x, it is replaced by JPA. More d
Session Facade is a design pattern to access enterprise bean through the local interface. It abstracts the business objec
interactions and provides a service layer. It makes the performance fast over the network.
o Entity
o EntityManager
o Persistence unit
o Data source
16) List down the steps for the demonstration of EJP persistence mechanism.
o Name
o mappedName
o Description
beanInterface
beanName
mappedName
o Default
o Class
o Method
20 Mention the Java types that can be mapped using the @Lob annotation.
o java.sql.Blob
o String
o byte[]
o java.sql.Clob
o Serializable Object
o Atomic
o Consistent
o Isolated
o Durable
Java Multithreading Interview Questions Java String & Exception Interview Questions
Latest Courses