EJB3 and JPA step by step tutorial using NetBeans

Here I explain step by step how to create an EJB 3 with JPA application in NetBeans IDE.
This tutorial is for beginners who want to learn steps to create EJB persistence application with NetBeans and Glassfish.

Tools used

NetBeans 6.9.1
Glassfish Server 3
MySQL database

Create an Enterprise Application called StudentManagementEA.

Create Enterprise Application in Netbeans




Click on images to enlarge











Create Enterprise Application in Netbeans


Create Enterprise Application in Netbeans
















It creates web module and EJB modules.

Now create a database called studentmgt_db. Go to services tab and create it.

Create database in Netbeans
























Again go to Projects tab and create Persistence Unit. It will generate the persistence.xml file.

Create persistence unit in Netbeans









Create persistence unit in Netbeans















Give a JNDI name and select data base you created.
Create persistence unit in Netbeans









Create persistence unit in Netbeans















It will generate an XML file called persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="StudentManagementEA-ejbPU" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/studentmgt</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
</persistence>

Then we have to create an Entity class.
  •  Entity Class must have @Entity annotaion
  •  Must have a public or protected no-arg constructor
  •  If it passed as a detached object through a remote interface, Must implement Serializable
  •  Must have an id annotated with @Id
I created a new java class called Student.java
package com.sameera.domain;

import java.io.Serializable;
import javax.persistence.*;

@Entity
@Table(name = "student")
public class Student implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Integer id;
    @Column(name = "first_name", length = 100)
    private String firstName;
    @Column(name = "last_name", length = 100)
    private String lastName;
    @Column(name = "email", length = 100)
    private String email;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public Integer getId() {
        return id;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}
Create  session beans.
Create a session bean in Netbeans















I create a Stateless session bean with Local interface.
Create a session bean in Netbeans


















It will generate ManageStudentSessionBean.java and ManageStudentSessionBeanLocal.java files.Then we can add business methods.Insert Code -> Add Business Method
















Give method name parameters and return types.




















ManageStudentSessionBeanLocal.java
package com.sameera.session;

import com.sameera.domain.Student;
import javax.ejb.Local;

/**
 *
 * @author Sameera Jayasekara
 */
@Local
public interface ManageStudentSessionBeanLocal {

    boolean addStudent(Student student);
    
}
ManageStudentSessionBean.java
package com.sameera.session;

import com.sameera.domain.Student;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Sameera Jayasekara
 */
@Stateless
public class ManageStudentSessionBean implements ManageStudentSessionBeanLocal {

    @PersistenceContext
    private EntityManager entityManager;

    public boolean addStudent(Student student) {

        entityManager.persist(student);

        return true;
    }
}
I didn't do exception handling and other stuff. Just added simple persist code and returned true.

Now you can deploy EJB module.











Now go to database view and see generated tables.














Now start working on web module.
In index file I created a form to fill data of a student and submit  to ManageStudentServlet. Add this code to index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>EJB3 JPA Glassfish - codesstore.blogspot.com</title>
    </head>
    <body>

        <form action="ManageStudentServlet" method="POST">

            <table border="0" width="100%">
                <tr>
                    <td colspan="3">  ${message}</td>
                </tr>
                <tr>
                    <td>First Name</td>
                    <td>:</td>
                    <td><input type="text" name="fname" value="" /></td>
                </tr>
                <tr>
                    <td>Last Name</td>
                    <td>:</td>
                    <td><input type="text" name="lname" value="" /></td>
                </tr>
                <tr>
                    <td>Email</td>
                    <td>:</td>
                    <td><input type="text" name="email" value="" /></td>
                </tr>
                <tr>
                    <td></td>
                    <td></td>
                    <td><input type="submit" value="Add" name="Add" /></td>
                </tr>
            </table>

        </form>

    </body>
</html>






Create  a servlet to handle the request.

Create a Servlet in Netbeans













I gave the name ManageStudentServlet

Create a Servlet in Netbeans

















Call to session beans in EJB module using dependancy injection
Insert Code -> Call Enterprise Bean









 Select ManageStudentSessionBean from list.







ManageStudentServlet.java
package com.sameera.controller;

import com.sameera.domain.Student;
import com.sameera.session.ManageStudentSessionBeanLocal;

import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 *
 * @author Sameera Jayasekara
 */

public class ManageStudentServlet extends HttpServlet {

    @EJB
    private ManageStudentSessionBeanLocal manageStudentSessionBean;


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String message = "";

        String firstName = request.getParameter("fname");
        String lastName = request.getParameter("lname");
        String email = request.getParameter("email");

        Student student = new Student();
        student.setFirstName(firstName);
        student.setLastName(lastName);
        student.setEmail(email);
       
        if (manageStudentSessionBean.addStudent(student)) {
            message = "Student Successfuly Added";
        } else {
            message = "Student Adding Failed";
        }

        request.setAttribute("message", message);
        RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
        rd.forward(request, response);

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }

}

web.xml configuration file looks like this.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>ManageStudentServlet</servlet-name>
        <servlet-class>com.sameera.controller.ManageStudentServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ManageStudentServlet</servlet-name>
        <url-pattern>/ManageStudentServlet</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>
Now deploy the web module and run EnterpriseApplication.
Check the database data will be added.

Note: I added MySQL connector mysql-connector-java-5.1.6-bin.jar  to .../GF3/domain1/lib folder in glassfish.Goto services tab and right click on glassfish -> properties find glassfish domain folder.

2 comments:

  1. Hi, greate tutorial. Can you add option to delete and update too.

    ReplyDelete
  2. nice tutorial.. I could get the basic concept of that...but now I am having problem to deploy the web module is giving me an error

    The module has not been deployed.
    See the server log for details.

    do you know What could be the possible problem of that??

    thanks

    ReplyDelete