JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven








Entity Bean in EJB3

Step By step EJB-JPA program

  • Jpa is used standalone and server side both
  • In server side it can be used with Servlet Jsp and Ejb

  • In this tutorial we will make the program for EjbJpa.
  • For Web Jpa we need to make a conection on to the server.
  • In this case we are using the glassfish server.
  • Start the server in the eclipse.
  • Right click and select the View Admin Console.




Connection Pool Creation In the glassfish server
  • A  admin console will get opened in the browser.
  • Exapand the  Resources-->JDBC  node.
  • Now select the  Connection Pools node.
  • Click on the New Button to create the new Connection Pool



  • Type the name as  mysql1
  • Select the Resource Type  as javax.sql.ConnectionPoolDataSource
  • Select the Mysql from the database Vendor.



  • Click on the Next Button.
  • Add the following properties for the JDBC Resources.
  • Click on the Finish button.
  • It will create  the mysql1



JDBC Resource Creation

  • After connection  pool creation we will create Jdbc Resource
  • Expand the JDBC Resources node.
  • Click on the new Button.


  • Type the JNDI name as jndi1.
  • Select the  Pool name as mysql1(earlier created)



  • Click on the Finish Button.
  • It will create JDBC Resourceon the glassfish server
  • This  will be used in persistence.xml for datasource element

Verification of  the Connection Pool Created

  • Navigate to the Connection Pool node.
  • Click on the created  Connection mysql1.
  • Navigate to the General tab
  • Click on the Ping button.
  • If it shows the Ping Succeeded Message 
     it means it is properly created
  • Else it can show the error message




  • Create a new EJB project
  • In this EJB project we will reate a session project




  • Type the Name of the projet as  EmployeeInfo.
  • Select the Server as glasfish .
  • Select add  projects to an EAR.
  • Type the name of the EAR project as EmployeeInfoEAR.




  • Check the Check Box to Create an EJB Client JAR module.
  • This will create a separate module.



  • This process creates a new EJB project.
  • Now we will create a session Beans.
  • Expand the Deployment Descriptor.
  • Right Click on the Session Beans
  • Select New-->Session Bean(EJB 3.x)





  • Select the Remote Interface.
  • This will create an remote interface
  • Select the state as Stateless.



  • Uncheck the
    • Inherited abstract methods
    • Constructors from the superclass

      Under Home and Components interface(EJB2.x)
    • This step will stop creation of home interface which is not required in ejb3.




  • Click on the Finish Button
  • This will create the following structure
  • Emp.java (stateless bean file) gets created in EmployeeInfo module
  • EmpRemote.java (Remote interface file) gets created in EmployeeInfoClient module




Adding JPA Facets
  • By default the Ejb project is not having JPA  properties.
  • So  user need to add the JPA  Facets to this project.
  • Right Click on the project.
  • Select the properties.
  • Here select the Project Facets.
  • Check the java Persistence.
  • Click on the Ok button.





Connecting the Connection
  • Below is one connection for mysql
  • Right click and select connect.
  • It will connect to the mysql database for the
    Connection New Mysql
  • How to  create  a new connection step by step click the link  below


    How to  create  a new connection




Entities Creation

  • Using the jpa tool we can create the Entity file.
  • Right click on the project.
  • Select the JPA tools-->Generate Entities from tables.




  • Here we are using the  Mysql  connection
  • This connetion is previously created.


    Creating the bean file
  • Select the schema test
  • Select the table as employee





  • Click on the Ok button.
  • It will create a new Entity(POJO) file.
package pack;

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


 
@Entity
@Table(name="employee")
public class Employee implements Serializable {
  private static final long serialVersionUID = 1L;

  @Id
  @Column(name="Eid")
  private int eid;

  private String name;

    public Employee() {
    }

  public int getEid() {
    return this.eid;
  }

  public void setEid(int eid) {
    this.eid = eid;
  }

  public String getName() {
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

}

  • Open the EmpRemote interface  present in 
    EmployeeInfoClient  module
  • Now add the code in the EmpRemote file.
  • We have added the methods to add, update, showall,
    remove, find  the records.

package pack;
import java.util.List;

import javax.ejb.Remote;

@Remote
public interface EmpRemote {

  void add(int eid,String name);
    List findall();
    List find(int eid);
    String remove(int eid);
    String change(int eid,String name);
    
}


  • Now open the Emp.java (Stateless bean file ) present in
    EmployeeInfo module.
  • Implement the methods of the RemoteInterface EmpRemote in Emp.java
  • We have implemented  the methods to add, update, showall,
    remove, find  the records.


package pack;

import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

 
@Stateless
public class Emp implements EmpRemote {

  @PersistenceContext(unitName = "emp")
    EntityManager em;
Employee emp;

  @Override
    public void add(int eid, String name) {
        emp=new Employee();
      emp.setEid(eid);
      emp.setName(name);
      em.persist(emp);
    }

    @Override
    public List<Employee> findall() {
      Query q = em.createQuery("select e from Employee  e");
      List<Employee> l =(List<Employee>q.getResultList();
      return l;
    }

    @Override
    public String change(int id, String name) {

      emp = em.find(Employee.class, id);
      if (emp == null)
     return "Id is not present";
      else {
        emp.setName(name);
        em.merge(emp);
        return "Record with" + id + " is updated ";
      }
    }

    @Override
    public List<Employee> find(int id) {
      List<Employee> list = new ArrayList<Employee>();

      emp = em.find(Employee.class, id);
      if (emp != null)
        list.add(emp);
      return list;
    }

    @Override
    public String remove(int id) {

      emp = em.find(Employee.class, id);
      
      String ret=null;
      if (emp == null)
        ret="Id is wrong";
      
      else if (emp != null) {
        em.remove(emp);
        ret="Record with id" + id + "  is deleted ";
      }
      return ret;
    }
}



persistence.xml
  • Open the persistence.xml.
  • Navigate to connection tab.
  • Type the JTA data source as jndi
  • This is the jdbc data source which we have created in the Admin console.




  • Click on the source tab
  • Add the persistence-unit name="emp" 
  • This persistence-unit name "emp" will be used in the Client file 

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd"
>
  <persistence-unit name="emp" transaction-type="JTA">
    <jta-data-source>jndi1</jta-data-source>
    <class>pack.Employee</class>
  </persistence-unit>
</persistence>


Dynamic Web Project

  • Type the Name of the projet as  EmployeeTest..
  • Select the Server as glasfish .
  • Select add  projects to an EAR.
  • Type the name of the EAR project as EmployeeInfoEAR.


  • This project will be used as the client for the Ejb project.
  • So set the Ejb Project in its classpath .
  • Right click on the EmployeeTest project.
  • Select the build path.


  • Navigate to Project tab.
  • Add the required Ejb Projects




  • Click on Ok.




index.jsp
  • Now we will create a jsp file
  • In this put the code  for the client to execute.
  • In its action type TestClient
<html>
<body>
<form action="TestClient">

Eid<input name="r"><br>
<br>

Name<input name="n"><br>
<br>

Select Option
<select name=
"op1">
  <option value="add">Add
  <option value="findall">FindAll
  <option value="change">Update
  <option value="delete">Remove
  <option value="find">Find
</select> 
<br><br>
<input type="submit"></form>
</body>
</html>


  • Now create one servlet cust_info.
  • put the code belowto add, show all, find, update and  remove the records.

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pack.Employee;
import pack.EmpRemote;

public class TestClient extends HttpServlet {
  private static final long serialVersionUID = 1L;

  @EJB
  EmpRemote std;

  protected void doGet(HttpServletRequest request,
      HttpServletResponse responsethrows ServletException, IOException {

    PrintWriter out = response.getWriter();
    response.setContentType("text/html");

    String op = request.getParameter("op1");
    if (op.equals("add")) {
      int roll = Integer.parseInt(request.getParameter("r"));
      String name = request.getParameter("n");

      std.add(roll, name);
      out.print("record inserted");
    }

    else if (op.equals("findall")) {

      List<Employee> st = std.findall();

      for (Employee emp : st) {
        out.print("<br><br>Eid---" +emp.getEid());
        out.print("<br>Name-----" + emp.getName());
      }
    else if (op.equals("find")) {
      int roll = Integer.parseInt(request.getParameter("r"));

      List<Employee> st = (List<Employee>std.find(roll);

      if (st.size() == 0)
        out.print("Record not available");
      else if (st != null) {
        for (Employee e : st) {
          out.print("Record is available");
          out.print("<br>Eid is  " + e.getEid());
          out.print("<br>Name is  " + e.getName());
        }
      }
    else if (op.equals("change")) {
      int roll = Integer.parseInt(request.getParameter("r"));
      String name = request.getParameter("n");
      String status = std.change(roll, name);
      out.print(status);
    }

    else if (op.equals("delete")) {
      int roll = Integer.parseInt(request.getParameter("r"));
      
      String status = std.remove(roll);
      out.print(status);
    }
  }
}


Running the program.
  • Right Click on  the index.jsp.
  • Select the Run On server.
  • Select the glassfish server.

  • Add the record




  • Add the record





  • Add the record










Download the EmployeeInfo code

Download the EmployeeInfoClient code

Download the EmployeeTest code

Download the EmployeeInfoEAR code