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 Spring MyEclipse

  • Create one java project
  • Add the name as Book Project.



  • Save it as BookProject.
  • Click on the finish button.





  • Adding JPA capabilities


  • Rt. Click on the project.
  • Select MyEclipse-->Add JPA Capabilities.





  • This will open the window.
  • In this window you can select the JPA provider.
  • We will select here  EclipseLink2.1.



  • Click on the next Button.
  • It will open the new window where user can create database connection.


Creating connection for database.

  • Here we are using MySQl database.
  • There is one table create.
  • One can also create using the  given command

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

mysql>


  • In this window we will create Connection.
  • Click on the Add Connection  Link



  • In the  coming window add the value for mysql databases.
  • Add the driver name, Driver template, user name, password and url.
  • Add the mysql connector jar file







Testing the connnection

  • Now we will test the connectioon.
  • Click on the TestDriver button.
  • It shows the message  Database connection successfully established.
  • Click on the finish button.
  • This step creates the connection as well as added JPA capabilities.




  • You can see the added EclipseLink  Jpa libraries.
  • Inside META-INF persistence.xml is also created.





Adding mysql connector file to our project

  • Right click on the project.
  • Select Build Path--->Add External Archives.




  • Creating Entity file from database

    • Now  right click on the project.
    • Select MyEclipse-->Generate Entities and DAOs.






  • Select the table from the given left frame.
  • Click on the Add button.





  • Type the java package as pack.
  • Select Update persistence.xml with generated entities.
  • Click  on the finish button.





  • It will create Book.java as shown below.
Book.java

package pack;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Book entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "book", catalog = "test")
public class Book implements java.io.Serializable {

  // Fields

  private Integer id;
  private String name;

  // Constructors

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

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

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

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

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

  @Column(name = "name")
  public String getName() {
    return this.name;
  }

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

}

  • Persistence.xml should be like this

persistence.xml

<?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_2_0.xsd"
     version=
"2.0">
    
  <persistence-unit name="BookProject"
    transaction-type="RESOURCE_LOCAL">
    <provider>
      org.eclipse.persistence.jpa.PersistenceProvider
    </provider>
    <class>pack.Book</class>
    <properties>
      <property name="javax.persistence.jdbc.driver"
        value="com.mysql.jdbc.Driver" />
      <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"/>
    </properties>
  </persistence-unit>

</persistence>



  • Create one TesBook.java in the package pack.
  • Add the code as shown below.
  • Use the  persistence-unit name="BookProject" in createEntityManagerFactory() method.


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

import pack.Book;

public class TestBook {

  EntityManagerFactory fac = null;
  EntityManager em = null;

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

  public TestBook() {
    fac = Persistence.createEntityManagerFactory("BookProject", 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.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();
    }
  }
}

Running the project

  • Right click on the TestBook file
  • Select run as -->java application

Output



Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
5
Book id is 797
Book name is name
Book id is 102
Book name is c++
Exit yes\no
no
Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
1
Enter Book Id
101
Enter Book name
java_programming
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_programming
Exit yes\no
yes