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 using  Hibernate

  • There are many tool for jpa developement.
  • One can use eclipse jpa., Apache open jpa and Hibernate jpa.
  • In this example we will make the use of Hibernate jpa.
  • In this  example we will use similar syntax as that of  eclipse jpa.
  • Only provider value in the persistence.xml will be changed.
  • In this case you have to make the use of  Hibernate jpa instead Eclipse jpa.





  • Now make the build path for the project
  • Right click and select Build Path-->Configure Build Path




  • JPA librrary files are presesnt on the jboss server.
  • So either use jboss run time or download the hibernate jar
    and set it into its build path.
  • Click on Add library.



  •  Select the Server Runtime.



  • Select the jboss server.
  • Jboss must be configured into your workspace.
  • If not configured then first add jboss to your workspace
    then add it as Runtime.




  • Click on the Ok Button.
  • It will add all library files of jboss server to your project classpath.



  • TO connect to the mysql server you need the mysql connector.
  • Add the mysql connector file.
  • To add click on the Add External JARS.
  • Select the mysql connector..
  • Click  on the OK button.




POJO  file creation


  • Create  one pojo file named as Book.java
  • Add it in a package jpahibernate.

  • Add the code as following


package jpahibernate;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;



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

  private Integer id;

  private String name;

  public Book() {
  }

  public Book(Integer id) {
    this.id = id;
  }

  @Id
  public Integer getId() {
    return id;
  }

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

  public String getName() {
    return name;
  }

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

}


Client File(TestBook.java)

  • Create one Test.java file inside the
    package jpshibernate.

  • Add the following code to access it.


package jpahibernate;

import java.util.List;
import java.util.Scanner;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import jpahibernate.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("JPAHibernatePU",
        System.getProperties());
    em = fac.createEntityManager();
    sc = new Scanner(System.in);
  }

  void addBook() {
    
    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.getTransaction().begin();
    em.persist(b);
    em.getTransaction().commit();
  
  }

  void delBook() {
    
    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.getTransaction().begin();
      em.remove(b);
      em.getTransaction().commit();
      System.out.println("Record removed");
    }
  }

  void findBook() {
    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();
    }
  }
}




Persistence.xml


  • Now create  one META-INF folder inside src directory.
  • Navigate to it
  • Create persistence.xml.


  • Add the following code.

<?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="JPAHibernatePU"
    transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>jpahibernate.Book</class>
    <properties>
      <property name="hibernate.connection.username" value="root" />
      <property name="hibernate.connection.driver_class"
                                          value=
"com.mysql.jdbc.Driver" />
      <property name="hibernate.connection.password" value="mysql" />
      <property name="hibernate.connection.url"
                                          value=
"jdbc:mysql://localhost:3306/test" />
      <property name="hibernate.cache.provider_class"
                                          value=
"org.hibernate.cache.NoCacheProvider" />
      <property name="hibernate.hbm2ddl.auto" value="update" />
    </properties>
  </persistence-unit>
</persistence>


Running the project

  • Right Click on the TestBook.java
  • Select Run As-->Java Appliction
  • It will run the jpa project.



  • Enter the data for differrent operations.
  • The code in the persistence.xml
 <property name="hibernate.hbm2ddl.auto" value="update" />
   will create table book in the mysql server in test database.
  • Get the data into database server.


Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
1
Enter Book Id
109
Enter Book name
qt
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 servlet
Exit yes\no
no
Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
4
Enter Book Id
101
Enter book name
Midlet
Book updated
Exit yes\no
no
Enter choice 1. Add 2. Remove 3. Find 4. Update 5. showAll
5
Book id is 11
Book name is c++
Book id is 101
Book name is Midlet
Book id is 103
Book name is php
Book id is 104
Book name is perl-cgi
Book id is 109
Book name is qt
Exit yes\no
yes

Download Eclipse code