ejb3

EJB Tutorial for Beginners

1. Introduction

Enterprise Java Beans (EJB) is a development architecture for building highly scalable and robust enterprise level applications to be deployed on JEE compliant Application Server such as JBOSS, Web Logic etc.

This tutorial explains basics about EJB3 and shows a simple work through to set up a EJB3 project, create a entity bean and a session bean.

EJB are primarily of three types which are briefly described below:

  1. Session Bean  Session bean stores data of a particular user for a single session. It can be stateful or stateless. It is less resource intensive as compared to entity beans. Session bean gets destroyed as soon as user session terminates.
  2. Entity Bean – Entity beans represents persistent data storage. User data can be saved to database via entity beans and later on can be retrieved from the database in the entity bean.
  3. Message Driven Bean  Message driven beans are used in context of JMS (Java Messaging Service). Message Driven Beans can consumes JMS messages from external entities and act accordingly.

2. Setup a new EJB Module

To create a simple EJB module, we’ll use NetBeans “New project” wizard. In example below, We’ll create a ejb module project named Sample-EJB.

Open NetBeans IDE, choose File > New Project.

In the New Project wizard, expand the Java EE category and select EJB Module as shown in the figure below. Then click Next.

Create EJB Module
Create EJB Module

You have to specify the Project Name and the Project Location in the appropriate text fields and then click Next.

Enter ejb project name
Enter ejb project name

In the next window, add the JEE Server and select the JEE version and click Finish.

Select Server
Select Server

3. Create a new Application Class Library Project

In this section you will create an application class library project for EJB remote interface and entity class.

Open NetBeans IDE, choose File > New Project.

In the New Project wizard, expand the Java category and select Java Class Library as shown in the figure below. Then click Next.

Create client project
Create client project

You have to specify the Project Name and the Project Location in the appropriate text fields and then click Next.

Enter client project name
Enter client project name

6
current project structure in netbeans

4. Create a sample Entity Bean

In this exercise you will create the Customer entity class. An entity class is a simple Java class that generally represents a table in a database. When you create the entity class, the IDE adds the @Entity annotation to define the class as an entity class. After you create the class, you will create fields in the class to represent the data that you want in your table.

Each entity class must have a primary key. When you create the entity class, the IDE adds the @Id annotation to declare which field to use as the primary key. The IDE also adds the @GeneratedValue annotation and specifies the key generation strategy for the primary Id.

To create the Customer class, perform the following steps.

  1. Right-click the Sample-Client in the Projects window and choose New > Other to open the New File wizard.
  2. From the Persistence category, select Entity Class and click Next.
  3. Type Customer for the Class Name.
  4. Type com.javacodegeeks.example.entity for the Package.
  5. Leave the Primary Key Type as Long in the New Entity Class wizard.
  6. Click Finish.

Create Entity class
Create Entity class

When you click Finish, the IDE creates the entity class Customer.java. The IDE opens Customer.java in the Source Editor.

In the Source Editor, perform the following steps.

  1. Add the following field declarations to the class:
        private String firstName;
        
        private String LastName;
  2. Right-click in the Source Editor and choose Insert Code (Alt-Insert; Ctrl-I on Mac) and select Getter and Setter to open the Generate Getters and Setters dialog box.
  3. Select the firstName and lastName fields in the dialog box. Click Generate. When you click Generate, the IDE adds getter and setter methods for the fields.
  4. Save the changes to Customer.java.

Customer.java

package com.javacodegeeks.example.entity;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author jGauravGupta
 */
@Entity
public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private String firstName;
    
    private String LastName;
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Customer)) {
            return false;
        }
        Customer other = (Customer) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.javacodegeeks.example.entity.Customer[ id=" + id + " ]";
    }

    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * @return the LastName
     */
    public String getLastName() {
        return LastName;
    }

    /**
     * @param LastName the LastName to set
     */
    public void setLastName(String LastName) {
        this.LastName = LastName;
    }
    
}

5. Create a sample Session Bean

The EJB 3.1 specification introduces @Stateless annotation that enables you to easily create stateless session beans. 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.

To create the stateless session bean, perform the following steps.

  • Right-click the EJB module and choose New > Other to open the New File wizard.
  • Select Session Bean in the Enterprise JavaBeans category. Click Next.

Create session bean
Create session bean

  • Type AccountService for the EJB Name.
  • Type com.javacodegeeks.example.service for the Package name.
  • Select Stateless.
  • Click Finish.

Enter ejb name and select type
Enter ejb name and select type

When you click Finish, the IDE creates the stateless session bean class and opens the class in the editor.

12
current project structure in netbeans

You can see that the IDE added the annotation @Stateless to the class to declare a stateless session bean.

Adding a Business Method

In this exercise you will create a simple business method in the session bean that returns a string.

  1. Right-click in the editor of AccountService and choose Insert Code (Alt-Insert; Ctrl-I on Mac) and select Add Business Method.

    Create business method
    Create business method
  2. Type createAccount for the Method Name.
    14
  3. Browse Customer entity for the Return Type and add parameter firstName and lastName.
    15
  4. Click OK.
    16

AccountService.java

package com.javacodegeeks.example.service;

import com.javacodegeeks.example.entity.Customer;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author jGauravGupta
 */
@Stateless
public class AccountService implements AccountServiceRemote {

    @PersistenceContext
    private EntityManager em;

    @Override
    public Customer createAccount(String firstName, String lastName) {
        Customer customer = new Customer();
        customer.setFirstName(firstName);
        customer.setLastName(lastName);

        em.persist(customer);

        return customer;
    }

}

6. Create Persistence Unit

In this exercise you will create a persistence unit to provide the container with information about the data source and how the entities are managed.

To create the Persistence Unit, perform the following steps.

  • Right-click the EJB module and choose New > Other to open the New File wizard.
  • Select Persistence Unit  in the Persistence category. Click Next.

Create persistence.xml
Create persistence.xml

In the [Provider and Database] step

  • Select persistence library.
  • Select database connection (e.g. some of sample database)

Click Finish to generate a default persistence.xml file with a default persistence unit (that will be configured later).

Enter persistence unit name
Enter persistence unit name

When you click Finish, the IDE creates persistence.xml. Select the Entity Bean class and add it to persistence unit :

Add entity class to persistence.xml
Add entity class to persistence.xml

Entity class added to persistence.xml
Entity class added to persistence.xml

7. Deploy the EJB Module

You can now build and deploy the EJB module. Right-click the Sample-EJB module and choose Deploy. When you click Deploy, the IDE builds the ejb module and deploys the JAR archive to the server.

In the Services window, if you expand the Applications node of GlassFish Server you can see that Sample-EJB was deployed.

8. Create a new Web Module

Open NetBeans IDE, choose File > New Project.

In the New Project wizard, expand the Java Web category and select Web Application as shown in the figure below. Then click Next.

Create new web application project to test ejb
Create new web application project to test ejb

You have to specify the Project Name and the Project Location in the appropriate text fields and then click Next.

Enter web project name
Enter web project name

In the next window, add the JEE Server and select the JEE version and click Finish.

Select server
Select server

9. Create a new Servlet Class to test EJB

In this exercise you will create a simple servlet to create the user account and to display the user id.

  • Right-click the Web module and choose File > New File wizard.
  • In the New File wizard, expand the Web category and select Servlet as shown in the figure below.
  • Then click Next.

Create new servlet
Create new servlet

You have to specify the Servlet Name, the Servlet Name and the Package Location in the appropriate text fields and then click Finish.

Enter servlet name
Enter servlet name

When you click Finish, the class AccountController.java opens in the Source Editor.

In the source editor, perform the following steps :

  • Right-click in the source editor
  • Choose Insert Code (Alt-Insert; Ctrl-I on Mac)
  • Select Call Enterprise Bean.

Call ejb
Call ejb

In the Call Enterprise Bean dialog box :

  • Expand the Sample-EJB node.
  • Select AccountService.
  • And click OK.

Add reference
Add reference

The dialog automatically selects Remote as the interface type. When you click OK, The IDE adds the @EJB annotation to inject the enterprise bean.

    @EJB
    private AccountServiceRemote accountService;

The IDE also automatically adds Sample-Client as a project Library.

The AccountServiceRemote session bean is instantiated and injected by the application server into the accountService field automatically (since the field is marked with the @EJB annotation).

AccountController.java

package com.javacodegeeks.example.tester;

import com.javacodegeeks.example.entity.Customer;
import com.javacodegeeks.example.service.AccountServiceRemote;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author jGauravGupta
 */
@WebServlet(name = "AccountController", urlPatterns = {"/AccountController"})
public class AccountController extends HttpServlet {
    @EJB
    private AccountServiceRemote accountService;
    
    /**
     * Handles the HTTP POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            String firstName = request.getParameter("firstName");
            String lastName = request.getParameter("lastName");
            
            Customer customer = accountService.createAccount(firstName, lastName);
            out.println("Customer["+customer.getFirstName()+"] : " + customer.getId());
        }
    }

}

10. Add a HTML Page

In this exercise you will create a simple html to submit user data to servlet.

  • Open NetBeans IDE, choose File > New File.
  • In the New File wizard, expand the Web category and select HTML as shown in the figure below.
  • Then click Next.

Create new HTML file
Create new HTML file

You have to specify the HTML file name and then click Finish.

Enter HTML file name
Enter HTML file name

23a
current project structure in netbeans

index.html

<!DOCTYPE html>
<html>
<head>
<title>Create Customer</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="AccountController" method="post" >
<input type="text" name="firstName" placeholder="First Name" />
<input type="text" name="lastName" placeholder="Last Name"/>
<input type="submit" value="Create"/>
</form>
</body>
</html>

11. Run the Project

You can now run the project. When you run the project, you want the browser to open to the page with the index.html. You do this by specifying the URL in the Properties dialog box for the web application. The URL is relative to the context path for the application. After you enter the relative URL, you can build, deploy and run the application from the Projects window.
To set the relative URL and run the application, do the following:

  • In the Projects window, right-click the Sample-Web application node
  • Select Properties in the pop-up menu.
  • Select Run in the Categories pane.
  • In the Relative URL textfield, type /index.html.
  • Click OK.

In the Projects window, right-click the Sample-Web application node and choose Run.
When you run the project, the index.html opens in your browser and displays the form to create user account.

HTML Form
HTML Form

When you create a user account, the AccountController Servlet is called to create user account and to display user id.

Output
Output

12. Download the NetBeans Project

Download the NetBeans project of this EJB tutorial:

Download
You can download the full source code of this example here: EJB_Example.zip

jGauravGupta

Gaurav is a senior software engineer with a passion for learning. He is an evangelist of netbeans & new technologies and author of JPA Modeler , jBatch Suite etc . He loves to go beyond the same old day to day work and find new and innovative ways to do the same things more effectively.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

9 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
abednego
abednego
6 years ago

hey my bean has failed to deploy

Luke
Luke
6 years ago
Reply to  abednego

me too. any hints to solve this problem? tnx!

Omalo
Omalo
6 years ago
Reply to  abednego

I can deploy my bean for you ;)

Pablo Reyes
6 years ago

excellent tutorial, thanks for the contribution!

Yan
Yan
6 years ago

Where is the defenition of the interface
AccountServiceRemote??

jugal kishor
jugal kishor
6 years ago

i have “HTTP Status 500 – Internal Server Error” error in htis project

John Smith
John Smith
4 years ago
Reply to  jugal kishor

added it to project:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>AccountController</servlet-name>
<servlet-class>com.javacodegeeks.example.tester.AccountController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AccountController</servlet-name>
<url-pattern>/AccountController</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

and will work, but I don’t see a response after adding a customer

John Smith
John Smith
4 years ago
Reply to  jugal kishor

else one moment you need add ejb project to web project as library, after it the project will work

Radoje
Radoje
4 years ago

Dear colleague Gaurav,

Thank you very much for the excellent tutorial.

Best regards,

Radoje

Back to top button