Wednesday, 7 June 2017

Simple Database Application using JPA

This tutorial is the third part in the series and shows you how to create a simple database application using JPA.  You can perform data insertion and retrieval operations using it. The application makes use of Servlet and JSP as server-side technologies and Java DB as the database with Netbeans 8.2 IDE. The tutorial assumes that you have basic understanding of Servlet and JSP technologies and familiarity with Netbeans IDE.

The Application

In this simple application, you will create an employee database to insert data into it using a JSP form.  When the JSP form is submitted, a servlet program is invoked to capture the form data and insert it into the database using JPA.  You can also invoke the servlet directly which displays the list of employees in the database using a JSP.  Different components of this simple application are shown in Figure-1.

Application Components
Figure-1:Application Components
Creating Database
In order to develop the application you need to create a database and an employee table with the following schema:
EMPLOYEE (EMPID INTEGER PK NOT NULL,
EMPNAME VARCHAR (50) NOT NULL,
DESIGNATION VARCHAR (20))

Creating Java Web Application Project
Now, create a new Web Application project following the below mentioned steps:
  1. Click on File > New Project (Ctrl + Shift + N) to open New Project window.  Under Categories, select JavaWeb. Under Projects, select Web Application. Click Next.
  2. In the Name and Location panel, type SimpleJPAApp in the Project Name field. Click Finish. The IDE creates SimpleJPAApp project.
Creating Persistence Unit
Now, create a persistence unit that represents the database. Follow the given steps to create it.
  1. Click on File > New File (Ctrl + N) to open New File window.  Under Categories, select Persistence. Under File Types, select Persistence Unit. Click Next.
  2. In the Provider and Database panel, see the IDE provides a default name SimpleJPAAppPU in the Persistence Unit Name field. Leave it like that. Also see the IDE shows EclipseLink (JPA 2.1) as the Persistence Provider.  This is the reference implementation of JPA and the IDE uses it as the default provider. Leave it like that.
  3. Now click on the Data Source dropdown box and select New Data Source. Create data Source dialog box opens.  Click on the Database Connection dropdown box and select ojhaDB. Provide empData as the JNDI Name   and click OK.  The name appears in the Data Source dropdown box.
  4. See that the IDE selects Use Transaction APIs checkbox by default.  Click the checkbox to deselect it. We shall use application-managed EntityManager and non-JTA based transaction management.  Now Click Finish. The IDE creates a persistence.xml file in the Configuration Files folder of the project.
Creating Entity class
Now, create an entity class representing the employee table following the steps given below:
  1. Click on File > New File (Ctrl + N) to open New File window.  Under Categories, select Persistence. Under File Types, select Entity Classes from Database. Click Next button.
  2. In the Database Tables panel, see that if empData is selected as the Data Source. Otherwise, select is from the dropdown box.
  3. From the Available Tables list click EMPLOYEE to select it and click on Add to move it to Selected Tables list.  Click Next button.
  4. In the Entity Classes panel, type entity in the Package dropdown box as the package name under which the entity class will be created.  Click Finish button. Employee.java file is created under the package.
  5. Double click Employee.java file to open it in the editor window. Click inside the class definition and right-click the mouse to open the popup menu. Click Insert Code… and then Constructor … to open Generate Constructor window. Select all the fields to be initialized by the constructor and click Generate button. A parameterized constructor is added to the generated code. This constructor will be used to create entity instances.

Creating JSP to enter data
Now, create a JSP file having an HTML form through which employee data will be added to the database.  Follow the steps given below to do so:

  1. Click on File > New File (Ctrl + N) to open New File window.  Under Categories, select Web. Under File Types, select JSP. Click Next button.
  2. In the Name and Location panel, type addEmployee in the File Name text filed and click Finish.
  3. Modify the addEmployee.jsp file to add an HTML form.  The form should include a table for better look.  You may use Pallet tool of the IDE to generate the form.  

If you are unable to use Pallet to generate code, then manually type the code. Your code should look like the following:

<h1>Add Employee</h1>
<form action="EmployeeServlet" method="POST">
      <input type="hidden" name="action" value="add" />
     <table border="1">
     <tr>
        <td>Employee ID</td>
        <td><input type="text" name="empid" value="" size="10" /></td>
     </tr>
     <tr>
       <td>Employee Name</td>
       <td><input type="text" name="empname" value="" size="25" /></td>
     </tr>
     <tr>
       <td>Designation</td>
       <td><input type="text" name="designation" value="" size="15" /></td>
    </tr>
    <tr>
     <td colspan="2" align="center"><input type="submit" value="ADD" /></td>
   </tr>
   </table>
</form>

See that one hidden form file with name=”action” and value=”add” is included in the code. This hidden form file is used to pass control information to the servlet program to execute conditional code meant for adding employee data in the table.

Creating Servlet to persist data

Now, create a servlet program to collect form data and enter into the table using JPA. Follow the steps given below to do so:

  1. Click on File > New File (Ctrl + N) to open New File window. Under Categories, select Web. Under File Types, select Servlet. Click Next button.
  2. In the Name and Location panel, type EmployeeServlet in the Class Name text filed and click Finish button. 
  3. Click inside the EmployeeServlet class definition and right-click the mouse to open the popup menu. Click Insert Code… and then Use Entity Manager… to add the following code to the class definition:

EntityManagerFactory emf =
    Persistence.createEntityManagerFactory("SimpleJPAAppPU");
public void persist(Object object) {
   EntityManager em = emf.createEntityManager();
    try {
            em.getTransaction().begin();
            em.persist(object);
            em.getTransaction().commit();
    } catch (Exception e) {
       Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            em.getTransaction().rollback();
   } finally {
            em.close();
   }
}

In the code, an instance of EntityManagerFactory is created associating the persistence unit, SimpleJAPAppPU.  The IDE generated persist() method creates an instance of EntityManager to add entity instances to the database using its persist() method. The persist operation is executed within a transaction demarcation.

4. Now remove all the code relating to HTML output and add the following code inside the try block of the processRequest() method:

     String action = request.getParameter("action");
            if (action.equals("add")) {
                int empId = Integer.parseInt(request.getParameter("empid"));
                String empName = request.getParameter("empname");
                String designation = request.getParameter("designation");
                Employee e = new Employee(empId, empName, designation);
                persist(e);
               getServletContext().getRequestDispatcher("/addEmployee.jsp").forward(request, response);
            }

This code is used to enter employee data into the database using JPA. It checks the control parameter, if its value equals to add then it retrieves form data and create an instance of the Employee entity using the parameterized constructor. Then it invokes the persist() method which was added in the previous step. Finally, it forwards the request to addEmployee.jsp. The request forwarding enables the application user to enter employee data again, if he wants to do so.

Modifying the Servlet to retrieve data

As said earlier, the application also retrieves all the employee data from the database. To do so, add the following code to the processRequest() method:

     EntityManager em = emf.createEntityManager();
     Query qry = em.createNamedQuery("Employee.findAll");
     List empList = qry.getResultList();
     em.close();
     request.setAttribute("list", empList);
     getServletContext().getRequestDispatcher("/listEmployee.jsp").forward(request, response);

This code is used to retrieves all employee data from the database using JPA. It creates an instance of EntityManager and then creates a named query using it.  The query execution returns a list of employees which is added to the request object. Then it forwards the request to listEmployee.jsp which in turn displays the employee list.

Creating JSP to display data

To display the employee data create listEmployee.jsp following the steps given below:


  1. Click on File > New File (Ctrl + N) to open New File window. Under Categories, select Web. Under File Types, select JSP. Click Next button.
  2. In the Name and Location panel, type listEmployee in the File Name text filed and click Finish. The listEmployee.jsp file is created.
  3. Modify the listEmployee.jsp file to add the following code:
<h1>List of Employees</h1>
<%
 List<Employee> employees = (List)request.getAttribute("list");
   for(Employee e: employees){
   out.println("<p>"+e.getEmpno()+" "+e.getEmpname()+" "+e.getDesignation()+"</p>");
   }
%>

The code retrieves the list object from the request object and displays employee entity details one at a time using a for loop.

Modifying files for navigation

To perform operations add and list smoothly, create a simple page navigation which is shown in Figure-2 and follow the steps:

1. Add the following HTML to the body tag of index.html file which is the default file created by the IDE.
<p>
   <a href="addEmployee.jsp">Add Employee</a><br>
   <a href="EmployeeServlet">List Employee</a>
</p>

2. Add the following HTML to the addEmployee.jsp file.

 <a href="EmployeeServlet">List Employee</a>

3. Add the following HTML to the listEmployee.jsp file.

  <p><a href="addEmployee.jsp">Add Employee</a></p>

Page Navigation
Figure-2: Page Navigation
Running the Application

Run the project and click the hyperlinks to add employees and then list the employees added to the database. Enjoy!

Conclusion

In this post, I showed you how to develop a simple JPA application. In the next post of this series, I will show how to perform basic CRUD operations taking a useful application. Keep reading my posts.

Share:

0 comments:

Post a Comment