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 program in 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 JPA project
  • This is used for creating default JPA project
  • Default JPAproject is standloane mode.






  • Type the name of the JPA project as BookDemo.
  • Select none as Target Runtime.
  • Click on the next.
Seloect the link .





  • 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 createa mysql connetion named as connection1




  • Click on the finish button
  • This will create a JPA Project.
  • 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 haeto populate it with the database.
  • For this action  click on the Populate from conection link



  • It opens a windowfor 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
  • work for the persistence.xml is ok.
  • 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="BookDemo" 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;
  }

}



Client file Creation
  • Now we will create a client file
  • In this we will give the code to add, show, update, delete records


import java.util.List;
import java.util.Scanner;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class TestBook {
  EntityManagerFactory fac = null;
  EntityManager em = null;

  int id;
  String name;
  Scanner sc = null;
  Book b = null;

  public TestBook() {
    fac = Persistence.createEntityManagerFactory("BookDemo",
        System.getProperties());
    em = fac.createEntityManager();
    sc = new Scanner(System.in);
  }

  void addBook() {
    em.getTransaction().begin();
    b = new Book();

    System.out.println("Enter Book Id");
    id = sc.nextInt();

    System.out.println("Enter Book name");
    name = sc.next();
    b.setId(id);
    b.setName(name);

    em.persist(b);
    em.getTransaction().commit();
  }

  void delBook() {
    em.getTransaction().begin();

    System.out.println("Enter Book Id");
    id = sc.nextInt();
    b = em.find(Book.class, id);

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

  void findBook() {
    em.getTransaction().begin();

    System.out.println("Enter Book Id");
    id = sc.nextInt();
    b = em.find(Book.class, id);

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

  void showAll() {

    List<Book> l = em.createQuery("select object(o) from Book as o")
        .getResultList();

    for (Book book : l) {
      System.out.println("Book id is " + book.getId());
      System.out.println("Book name is " + book.getName());
    }
  }

  void updateBook() {
    em.getTransaction().begin();
        b=new Book();
        
    System.out.println("Enter Book Id");
    id = sc.nextInt();
    b = em.find(Book.class,id);

    if (b == null)
      System.out.println("Record is not present");
    else {
      System.out.println("Enter book name");
      name = sc.next();
      b.setName(name);
      em.merge(b);
      em.getTransaction().commit();
      System.out.println("Book updated");
    }
  }

  public static void main(String[] args) {

    String ch = "no";
    TestBook mybook = new TestBook();

    while (!ch.equals("yes")) {
      int x;
      System.out
          .println("Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll");
      x = mybook.sc.nextInt();

      if (x == 1)
        mybook.addBook();

      else if (x == 2)
        mybook.delBook();

      else if (x == 3)
        mybook.findBook();
      
      else if (x == 4)
        mybook.updateBook();
      
      else if (x == 5)
        mybook.showAll();
      
      System.out.println("Exit yes\\no");
      ch = mybook.sc.next();
    }
  }
}

  • Run the above file and add the  operation values as  shown below.

Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
1
Enter Book Id
101
Enter Book name
java
Exit yes\no
no

Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
1
Enter Book Id
102
Enter Book name
c++
Exit yes\no
no

Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
1
Enter Book Id
103
Enter Book name
perl
Exit yes\no
no

Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
5
Book id is 101
Book name is java
Book id is 102
Book name is c++
Book id is 103
Book name is perl
Exit yes\no
no

Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
3
Enter Book Id
101
Book detail is
Book id is 101
Book name is java
Exit yes\no
no

Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
4
Enter Book Id
101
Enter book name
jpa
Book updated
Exit yes\no
no

Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
5
Book id is 101
Book name is jpa
Book id is 102
Book name is c++
Book id is 103
Book name is perl
Exit yes\no




Download the code