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









JPA on Tomcat

 Using  Eclipse  step by step

  • JPA in standalone mode
    • Jpa is used both as standloane and server side.
    • There are serveral tools which can be used for JPA program creation.
    • Most used tools are Eclipse Link,  Hibernate JPA, TOP Link JPA
    • In this program we will use the Eclipse Link tool for jpa program


  • First take a Dynamic  project.
  • Type the name of the project as 
  • Select server as tomcat.







  • Now we will either give the library path  or  download it.
  • Select The EclipseLink 2.1x
  • Click on the download button asshown below





  • It opens another window
  • In this window select the Eclipse Library Version.
  • Click on the Next Button




  • Now select the check box to accept the licence.
  • Click on the Next button.



  • It will download the eclispeLink2.1x library from the site.
  • Select the downloaed Usr Library



  • Click  on the Add Connection  link to add a new
    connection for the specific database.
  • In the upcoming  window select  the required dtabase softare
  • We will select the  Mysql database.





  • Type the name of the connection as connection1
  • Click on the next Button.


  • In the given window type the given database
  • In the url section type the url.
  • In the User Name type the user name of Mysql
  • In the Password section type the password
  • Check the save password



  • Click on the Test Connection button to check   the proper setting.
  • If the setting is accurate it will display the Ping Succeeded message.
  • Click on the Ok button




  • Now you can add the jar files for the mysql.
  • In the Driver Section Click on the New Driver button
    a shown below.



  • Here select the MyQL JDBC Driver 5.0
  • Click on the Jar List tab.





  • Select the previous jar file and click on the remove butoon to remove it.
  • Click on the Add jars
  • Select the mysql conector jar file from your computer.



  • Click on the Properties tab.
  • Here  reviewthe user, password, url and Driver name
  • Click on the Ok button.




  • It will create a mysql connetion named as connection1




  • Click on the finish button
  • This will create a Dynamic project with  JPA facility..




  • This project ishaving jpa facilities.
  • It has one JPA  folder which contains persistence.xml file


  • Open the persistence.xml
  • navigate to Conection tab
  • It is having default Transation type as Dfault(JTA) .
  • JTA transaction type is  for the server type connetion



  • We need to change it to  Resource Local.
  • Now we have to populate it with the database.
  • For this action  click on the Populate from conection link



  • It opens a window for selecting the connection.
  • Select here connetion1 which we have just created.



  • This opens the  connection values
  • Click on the save button




  • Navigate to  General tab
  • Here we will give the value for the persistence provider.
  • Just type the org.eclipse.persistence.jpa.PersisteneProvider.
  • Click on the save button.
  • You can see the source code for the persistence.xml in the source tab.


<?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="TomcatJPA" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>Book</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
      <property name="javax.persistence.jdbc.password" value="mysql"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
    </properties>
  </persistence-unit>
</persistence>

Table creation in MySql

mysql> use test;
Database changed
mysql>
mysql> create table book (id int primary key, name char(12));
Query OK, 0 rows affected (0.02 sec)


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.



  • In this  window select  the Connection conection1.
  • Slect the schema as test.
  • Schema  is the database name of mysql here.
  • After that it will show the table names
  • Select the table name as book.




  • Click on the Ok button
  • It will create a Entity(POJO) file with the given code.

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


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

  private int id;

  private String name;

    public Book() {
    }
     @Id
  public int getId() {
    return this.id;
  }

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

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

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

}



Jsp and Servlet Creation
  • Now we will create a jsp file for the form
  • Right click on the project and select New jsp file.
  • Name it as index.jsp.
  • Add the code given below.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

  <body>
    <h1>
      Book Details
    </h1>

    <form action="TestBook">
      <table>
        <tr>
          <td>
            ID
          </td>
          <td>
            <input name="id">
          </td>
        </tr>

        <tr>
          <td>
            Name
          </td>
          <td>
            <input name="name">
          </td>
        </tr>


        <tr>
          <td>
            select operation
          </td>
          <td>
            <table>
              <tr>
                <td>
                  <input type="radio" name="choice" value="add" />
                </td>
                <td>
                  Add
                </td>
              </tr>

              <tr>
                <td>
                  <input type="radio" name="choice" value="find" />
                </td>
                <td>
                  Find
                </td>
              </tr>

              <tr>
                <td>
                  <input type="radio" name="choice" value="update" />
                </td>
                <td>
                  Update
                </td>
              </tr>

              <tr>
                <td>
                  <input type="radio" name="choice" value="delete" />
                </td>
                <td>
                  Delete
                </td>
              </tr>

              <tr>
                <td>
                  <input type="radio" name="choice" value="findall" />
                </td>
                <td>
                  FindAll
                </td>
              </tr>


            </table>
          </td>
        </tr>
        <tr>
          <td></td>
          <td>
            <input type="submit" value="OK">
          </td>
        </tr>

      </table>
    </form>

  </body>
</html>


  • Now we will create a Servlet file for the form action.
  • Right click on the project and select New Servlet file.
  • Name it as TestBook.java.



  • Add the code given below.



import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestBook extends HttpServlet {

  EntityManagerFactory fac = null;
  EntityManager em = null;
  EntityTransaction tr;

  int id;
  String name;
  Book b = null;

  public TestBook() {
    fac = Persistence.createEntityManagerFactory("TomcatJPA");
    em = fac.createEntityManager();
    tr = em.getTransaction();
  }

  void addBook(int id, String name, PrintWriter out) {
    tr.begin();
    b = new Book();
    b.setId(id);
    b.setName(name);

    em.persist(b);
    tr.commit();
    out.print("Record added");
  }

  void delBook(int id, PrintWriter out) {
        
    b = em.find(Book.class, id);

    if (b == null)
      out.println("record not present");
    else {
      tr.begin();
      em.remove(b);
      tr.commit();
      out.println("Record removed");
    }
  }

  void updateBook(int id, String name, PrintWriter out) {
    b = em.find(Book.class, id);

    if (b == null)
      out.println("Record is not present");
    else {
    tr.begin();
    b = new Book();
    b.setId(id);
    b.setName(name);

    em.persist(b);
    tr.commit();
      out.println("<br>Record updated with id  " + id);
    }
  }

  void deleteBook(int id, PrintWriter out) {
    b = em.find(Book.class, id);

    if (b == null)
      out.println("Record is not present");
    else {
      tr.begin();
      em.remove(b);
      tr.commit();
      out.println("<br>Record removed " );
    }
  }

  void findBook(int id, PrintWriter out) {
    b = em.find(Book.class, id);

    if (b == null)
      out.println("Record is not present");
    else {
      out.println("Book detail is ");
      out.println("<br>Book id is " + b.getId());
      out.println("<br>Book name is " + b.getName());
    }
  }

  
  void findAll(PrintWriter out) {
      List<Book> l = em.createQuery("select b from  Book b")
          .getResultList();

      for (Book bk : l) {
        out.print("<br><br>Book id is " + bk.getId());
        out.print("<br>Name is " + bk.getName());
      }
    }
  

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

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

    String choice = request.getParameter("choice");

    
    if(choice.equals("add")){
          int id = Integer.parseInt(request.getParameter("id"));
    String name = request.getParameter("name");

      addBook(id,name,out);
    }
    else  if(choice.equals("find")){
        int id = Integer.parseInt(request.getParameter("id"));
           findBook(id, out);
    }
    else  if(choice.equals("update")){
        int id = Integer.parseInt(request.getParameter("id"));
    String name = request.getParameter("name");

      updateBook(id, name, out);
    }
    else  if(choice.equals("findall"))
      findAll(out);
    
    else  if(choice.equals("delete")){
        int id = Integer.parseInt(request.getParameter("id"));

      deleteBook(id, out);
    }
  
  }
}

  • Right click on the index.jsp.
  • Select Run As--->Run On Server.
  • Select Tomcat server.
  • Click on the finish Button.







  • Add the values as shown above.
  • Select the Add Button.
  • Click on the OK button.




  • Record will be added into the mysql database.
  • You can try all the options.

Download the Eclipse code