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 MyEclipse

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 TOPLink JPA tool for jpa program


  • First take a new Java ProjectJPA project



  • Type the name of the java project as PorjectJPA.
  • Click on the next.



  • It will create a new Java Project.
  • By default this project is not having jpa capability.
  • It has to be added.

Database Table Creation

mysql> use test;
Database changed
mysql>

mysql> Create table project1(id int primary key, name char(12));
Query OK, 0 rows affected (0.00 sec)


Adding JPA capability.

  • Now we will add the jpa capability to our created program.
  • Right Click on the Project.JPA.
  • Select  MyEclipse-->Add JPA capabilities.
  • Do as shown below.



  • Now select the jpa provider.
  • Here you can take the TopLink  or Hibernate jap provider.
  • If you are using other then you can select other.



Configuring Persistence Unit
  • We will create the new Driver configuration for our project.
  • Click  the link   Create new Driver.

.


  • It will open the  window for Driver configuration.
  • We will use the mysql configuration.
  • We will select here MySQL Connector/J from Driver template option.

  • Add the driver name.
  • Add the user name and password for the mysql database database.
  • Also add the Connection URL.
  • Now click opn the Add   JARs button.
  • Select the mysql connector jar file from your computer.




  • It is showing the mysql connector jar files.
  • Now the driver name is also filled up with
    com.mysql.jdbc.Driver.
  • Clck on next button.




  • Now select the Drive name
  • Check the Copy DB driver jars to project.
  • Click on the Update List button.
  • It will show the database (schema) name.
  • Select the test database name.
  • Click on the finish button.



  • It will create the project  with the folder META-INF
    having persistence.xml file.
  • Now the project is having TOPLink jar files.
  • It is also having the mysqlconnector files.




Creating the Entity  file.

  • Now we will create the Entity  file from the database table.
  • Right click on the Project.
  • Select the MyEclispe-->Generate Entities.




  • Select the table from the given window.
  • Click on the add button.



  • Select the Entity Bean generation.
  • Select the Check box Update persistenc.exml with generated entities.
  • So after creation of the Entity file its value will be added into the persistence.xml.
  • Click on the finish button.
  • It will create Project.java file as Entity file.




  • Now  the project  is showing the created file.


Porject.java

This Entity file is having the following code.


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "project", catalog = "test", uniqueConstraints = {})
public class Project implements java.io.Serializable {

  // Fields

  private Integer id;
  private String name;

  // Constructors

  /** default constructor */
  public Project() {
  }

  /** minimal constructor */
  public Project(Integer id) {
    this.id = id;
  }

  /** full constructor */
  public Project(Integer id, String name) {
    this.id = id;
    this.name = name;
  }

  // Property accessors
  @Id
  @Column(name = "id", unique = true, nullable = false, insertable = true,
    updatable = 
true)
  public Integer getId() {
    return this.id;
  }

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

  @Column(name = "name", unique = false, nullable = true, insertable = true,
    updatable = true, length = 
12)
  public String getName() {
    return this.name;
  }

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

}


persistence.xml

  • The persistence.xml is having the provider as toplink.
    <provider>

          oracle.toplink.essentials.PersistenceProvider
    </provider>
        
  • class is having value as  Project.java  in the class tag
    <class>Project</class>

<?xml version="1.0" encoding="UTF-8"?>
<persistence 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" version="1.0">
    
  <persistence-unit name="PorjectJPAPU"
    transaction-type="RESOURCE_LOCAL">
    <provider>
      oracle.toplink.essentials.PersistenceProvider
    </provider>
    <class>Project</class>
    <properties>
      <property name="toplink.jdbc.driver"
        value="com.mysql.jdbc.Driver" />
      <property name="toplink.jdbc.url"
        value="jdbc:mysql://localhost:3306/test" />
      <property name="toplink.jdbc.user" value="root" />
      <property name="toplink.jdbc.password" value="mysql" />
    </properties>
  </persistence-unit>

</persistence>

Client file.
  • Create a file named  TestProject.
  • Add the coding as given below.
  • This code contains CRUD operations for the data.


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

public class TestProject {

  EntityManagerFactory fac = null;
  EntityManager em = null;

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

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

  void addProject() {
    em.getTransaction().begin();
    b = new Project();

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

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

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

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

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

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

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

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

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

  void showAll() {

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

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

  void updateProject() {
    em.getTransaction().begin();
    b = new Project();

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

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

  public static void main(String[] args) {

    String ch = "no";
    TestProject myProject = new TestProject();

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

      if (x == 1)
        myProject.addProject();

      else if (x == 2)
        myProject.delProject();

      else if (x == 3)
        myProject.findProject();

      else if (x == 4)
        myProject.updateProject();

      else if (x == 5)
        myProject.showAll();

      System.out.println("Exit yes\\no");
      ch = myProject.sc.next();
    }
  }
}


Running the project.
  • Now we will run the project.
  • Right Click on the TestProject file.
  • Select Run As-->Java Application. 



  •  Add the values as  given below.
  • Use all the crud operations.

[TopLink Info]: 2011.09.15 03:01:27.625--ServerSession(7726332)--TopLink, version: Oracle TopLink Essentials - 2.0 (Build b40-rc (03/21/2007))
[TopLink Info]: 2011.09.15 03:01:28.515--ServerSession(7726332)--file:/C:/Documents%20and%20Settings/shankar/workspacemyEc/PorjectJPA/bin/-PorjectJPAPU login successful
Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
1
Enter Project Id
101
Enter Project name
java
Exit yes\no
no
Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
1
Enter Project Id
102
Enter Project name
php
Exit yes\no
no
Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
5
Project id is 202
Project name is java project
Project id is 101
Project name is java
Project id is 102
Project name is php
Exit yes\no
yes



  • From MySql you can check the values.
  • Select the values  that has been inserted.





mysql> Select * from project;
+-----+--------------+
| id  | name         |
+-----+--------------+
| 202 | java project |
| 101 | java         |
| 102 | php          |
+-----+--------------+
3 rows in set (0.05 sec)


Download Eclipse code