JavaRush /Java Blog /Random EN /Introduction to EJBs
Анзор Кармов
Level 31
Санкт-Петербург

Introduction to EJBs

Published in the Random EN group
In this article, we will consider EJB - Enterprise JavaBeans. This technology is part of the Java EE specification. We will touch on issues such as:
  • what is an EJB;
  • what is the history of the emergence of EJB;
  • what are the types of EJBs.
And also - we will write a small HelloWorld application using EJBs and servlets. Introduction to EJBs - 1This article will be useful to readers who have mastered Java SE and are starting to learn Java EE. For a full understanding of the practical part of this article, it is recommended that you first read the article “ Setting up a local environment ”.

A Brief History of EJBs

Back in 1996, when the author of this article was 5 years old, Java was already popular among developers. The reason for this was the friendly API, automatic garbage collection, etc. Java was widely used in backend systems. However, despite all the charms of the language, programmers of that time needed certain functionality that was not yet implemented in the JDK. These needs were:
  • ensuring data persistence;
  • transaction integrity
  • concurrent access to data (management of multithreading);
  • and most likely something else.
All this led to a natural growth in the population of home-grown, self-written, closed libraries. In other words, everyone realized their needs as best they could. This continued until IBM in 1997 came up with the slogan "Everyone should fulfill their needs the same" and released the Enterprise Java Bean (EJB) specification. It was she who made it possible to unify the development process and take the solution of typical problems (described above as needs) on the side of the framework. Sun has been adapting the brainchild of IBM for 2 years, and in 1999 released the EJB 1.0 specification. This is how the technology was born, which will be discussed in a more applied way.

What is EJB

In a sense, EJB is a collective term that, depending on the context, can mean either the Enterprise JavaBeans technology itself in general, or some specific Enterprise JavaBean software component (bean) that is part of the EJB technology. The definition of EJB as a technology is given on Wikipedia: Enterprise JavaBeans (also often used as an abbreviation of EJB) is a technology specification for writing and supporting server components containing business logic. It is part of Java EE. This technique is typically used when business logic requires at least one of the following services, and often all of them:
  • support for data persistence: data must be preserved even after the program is stopped. Most commonly achieved using a database;
  • support for distributed transactions;
  • support for parallel data modification and multithreading;
  • event support;
  • naming and directory support (JNDI);
  • security and restriction of access to data;
  • support for automated installation on the application server;
  • remote access.
The services listed above are the undoubted advantage of EJB technology. Another such advantage is that all of the above works out of the box, right away. Those. the programmer does not need to think about supporting distributed transactions. The programmer only needs to think about the business logic he is currently trying to implement. An EJB as a specific software component is a Java class with one or more annotations from the EJB specification that contains some of the application's business logic. Annotations from the EJB specification endow the labeled class with certain powers, powers, and superpowers. Read more about this below.

EJB Types

Let's summarize. An EJB is a regular Java class marked with one of the special annotations. Such classes are called beans. Depending on what annotation the class is marked with, it will be a representative of one or another type of EJB (beans). There are three main types of beans:
  • Message Driven Beans (message driven beans);
  • Entity Beans (object beans) - defined in the JPA (Java Persistence API) specification and used to store data;
  • Session Beans (session beans).
The latter (session beans) are divided into several subspecies:
  • stateless (without state);
  • stateful (supporting the current state of the session);
  • singleton (one object per application; starting with EJB 3.1).
Introduction to EJBs - 2Let's look at each type of bean in more detail below.

Session Beans

Session Beans, or session beans - a certain kind of beans. They encapsulate the business logic that the client can programmatically call by calling the methods of this bean. A method call can do:
  • locally, by another class in the same JVM as the session bean;
  • remotely, over a network, from another JVM, using Java RMI (Remote Method Invocation) technology.
The word "session" suggests that the bean is available only for the duration of a certain task by the server and is irretrievably destroyed in the event of a crash or server shutdown. The life cycle of a session bean instance is managed by the EJB container (you can read more about EJB containers in the first lecture of the cycle ). Stateless session beansdo not store information about their state. This type of component can be used by different clients. Stateless beans are used to implement business processes that can be completed in a single operation. For example, checking the credit history of customers. Because a single instance of a bean can be used by multiple clients, the developer must provide thread-safe access to the bean's data. Creating a bean of this type (however, like all other session beans) is quite simple. This is a normal Java class with the annotation @Stateless. Let's take an example below:
import javax.ejb.Stateless;

@Stateless
public class StatelessEjbExample {
    public String sayHi() {
        return "Hi, I'm Stateless EJB!";
    }
}
Session beans with support for the current state of the session (Stateful) retain information about their state between accesses to it from the same client and terminate their existence upon an explicit request from the client. This is achieved due to the fact that stateful beans are unique for each client. An example of a task that this type of bean can be responsible for is keeping a shopping cart in an online store up to date for each user. The bean data lifecycle is managed by the EJB container. These beans are also destroyed when the client exits. Such beans are also quite simple to create. This is a Java class annotated with Stateful. Example below:
import javax.ejb.Stateful;

@Stateful
public class StatefulEjbExample {
    public String sayHi() {
        return "Hi, I,m Stateful EJB";
    }
}
Session beans of a singleton (singleton) are initiated once during the lifetime of the application and exist for the entire lifetime of the application. Such beans are designed for situations in which one state must be shared among all clients. Like stateless beans, in singleton beans, the developer needs to monitor the organization of a thread-safe environment inside the bean. Let's give an example of a Singleton bean, which is just as easy to create as its counterparts, which were discussed above. It is not difficult to guess that this is a Java class with the annotation @Singleton. However, in this case, you need to be careful. There are two annotations, identical in syntax, but different in purpose and located in different packages:
  • javax.ejb.Singleton
  • javax.inject.Singleton
To create an EJB, you need to use an annotation from the javax.ejb. Example below:
import javax.ejb.Singleton;

@Singleton
public class SingletonEjbExample {
    public String sayHi() {
        return "Hi, I'm Singleton EJB!";
    }
}

Message Driven Beans

Message Driven Beans, or MDBs, or message driven beans, like session beans, implement some business logic. But unlike its relatives, MDB has one important difference. Clients never call MDB methods directly. Such beans most often act as listeners for JMS (Java Message Service) messages and serve to organize asynchronous messaging between parts of the system. An example of such a message would be a request for the delivery of inventory from an automated retail system to a supply chain management system. Below is an example of an MDB bean. Unlike session beans, its creation is a bit more interesting:
import javax.annotation.Resource;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

@MessageDriven(mappedName = "jms/TestQueue")
public class MessageDrivenEjbExample implements MessageListener {

    @Resource
    private MessageDrivenContext messageDrivenContext;

    public void onMessage(Message message) {
        try {
            if (message instanceof TextMessage) {
                TextMessage msg = (TextMessage) message;
                msg.getText();
            }
        } catch (JMSException e) {
            messageDrivenContext.setRollbackOnly();
        }
    }

}
The annotation MessageDrivenmakes our MDB class a bean. Inside the annotation, using JNDI (read about JNDI here ), the name of the JMS mailing list is determined, the listener of which our class becomes. In addition, our class implements the interface MessageListenerand its method onMessage. This method will be called when some message arrives from the queue/distribution with the name defined inside the annotation MessageDriven.

Entity beans

Part of the EJB technology is the JPA specification. JPA, or Java Persistence API, is a specification that provides object-relational mapping (ORM - Object-Relational Mapping) of Java objects (Entity beans) and provides an API for saving, retrieving and managing such objects. JPA allows you to represent data from a database as Java objects, as well as store Java objects as records in the database. Not every class can act as such an object, but just Entity beans. Entity Bean is a Java class that is a representation of some table in a database. Display (mapping) is achieved through the use of special annotations. With their help, a comparison of a Java class with a table in the database is carried out, as well as a comparison of the fields of the Java class with the fields of the database table. Here is an example of an Entity bean,
@Entity // Делает данный класс Entity бином
@Table(name = "employee") // "Связывает" данный класс с таблицей employee в БД
public class Employee implements Serializable {

    @Id // Говорит о том, что поле ниже является первичным ключом
    @GeneratedValue(strategy = GenerationType.AUTO) // Определяет тип генерации значений первичного ключа
    private int id;

    @Column(name="name") // "Связывает" поле ниже с полем name в таблице employee в БД
    private String name;

    @Column (name="age") // "Связывает" поле ниже с полем age в таблице employee в БД
    private int age;

    // getters and setters...
}
It is worth noting that this type of bean makes sense to study only in the context of studying the JPA specification.

Writing an application: EJB HelloWorld

In this section, we will write a small Java EE HelloWorld application that we will deploy to the GlassFish server. Before reading this article, it is strongly recommended that you read the article on configuring the local environment .
  1. Create a new Maven project in IntelliJ IDEA.

    File -> New -> Project...

    Introduction to EJBs - 3
  2. Click Next .

  3. Fill in the Maven project parameters:

    Introduction to EJBs - 4
  4. Click Finish

  5. The project is created and has the following structure:

    Introduction to EJBs - 5
The pom.xml file looks like this: Introduction to EJBs - 6First of all, we need to add a dependency on the Java EE API and specify how to package our project as a web application archive (war). To do this, you need to bring the pom.xml code to the following form:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.codegym.lectures</groupId>
    <artifactId>ejb_demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>
    </dependencies>

</project>
Next, you can proceed to the Java code. Our application will be the simplest. We will have 1 servlet and 1 EJB. This will be a stateless session bean. Inside the EJB, we will define only 1 method that will return the string "Hello World". First of all, let's create a package com.codegym.lectures. Then, inside the package com.codegym.lectures, let's create our bean - DemoEJB. The bin code is shown below:
import javax.ejb.Stateless;

@Stateless
public class DemoEJB {
    public String helloWorld() {
        return "Hello world!";
    }
}
As mentioned earlier, everything is quite simple. Our next step is to create a servlet that will pass the value from the EJB as a response to the HTTP request. It's worth noting that servlets are out of the scope of this article, but you'll still need to use them to demonstrate EJBs. To do this, let's create a new servlet DemoServletin the same package as the EJB. Its code is below:
@WebServlet("/helloWorld")
public class DemoServlet extends HttpServlet {

    @EJB
    private DemoEJB ejb;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write(ejb.helloWorld());
    }
}
Let's give small comments to the code. Annotation @WebServlet("/helloWorld")- defines our class as a servlet that will process HTTP requests to the endpoint /helloWorld. Our class has one field - DemoEJB ejb. This is our bean defined earlier. An annotation over a class field - @EJBperforms dependency injection (DI). Those. The ejb variable is automatically initialized to a new instance when needed. Our class inherits from HttpServlet and overrides one of the superclass methods, doGet. This method processes HTTP GET requests and takes two parameters - HttpServletRequestand HttpServletResponse. HttpServletRequestis used to get information about an incoming HTTP request. HttpServletResponseneeded to generate a response to a query. Inside the method, we get an object PrintWriterfrom the response object (HttpServletResponse), using the method getWriter(). Next, we can write some value to the resulting object using the write. Which, in fact, we use by writing to the object PrintWriter-a the value obtained from the EJB we defined (the value is the string “Hello World!”). The client that sent the HTTP request will receive this value as a response to its request. The next step is to run the application on the GlassFish Java EE server. To do this, let's create a new configuration, as described in the article on setting up a local environment . Below is a screenshot of the finished configuration for the current project. Make sure you have the GlassFish server installed before launching: Introduction to EJBs - 7After creating the launch configuration, launch the application using the menu Run -> Run 'ejb_demo' or using the hotkeyShift+F10 . After launch, you can see its logs: Introduction to EJBs - 8As well as the opened browser: Introduction to EJBs - 9All this indicates that the application is working as intended. Introduction to EJBs - 10

Conclusion

In this article, we got acquainted with EJB - Enterprise JavaBeans. Considered questions such as:
  • What is EJB?
  • History of EJBs
  • Different types of EJBs
Recall that EJBs are of the following types:
  • Message Driven Beans (message driven beans);
  • Entity Beans (object beans) - defined in the specification JPA (Java Persistence API) entities and are used to store data;
  • Session Beans (session beans):
    • stateless (no state)
    • stateful (supporting the current state of the session)
    • singleton (one object per application; since EJB 3.1)
We also wrote a small HelloWorld application using EJBs. As a DZ, you can repeat the practical part of this article yourself. And then add two more servlets to your application that will use the stateful and singleton beans to get the value.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION