Java Persistence (JPA) Tutorial With Hibernate

JPA Tutorial With Hibernate explains step by step details of setting / configuring Java Persistence (JPA) With Hibernate And Eclipse

How To Configure Hibernate (JPA) With Oracle Database?

Java Persistence API (JPA), is a standard interface which wraps different ORM tools such as  Hibernate, EclipseLink, OpenJPA etc. The benefits of using JPA is that you can change the underlying implementation of without changing any code.

ie; you can able to change Hibernate implementation to EclipseLink implementation without changing the code base.

On this standalone JPA Example, we are using Java Persistence (JPA) With Hibernate

Hibernate is popular open source ORM (Object Relation Mapping) tool for Java platform, for mapping an entity to a traditional relational database like Oracle, MySQL etc

By using JPA, we can do database operations like Create, Read, Update & Delete etc, with very little code.

Required Libraries

You need to download

  1. JDK 6
  2. Eclipse 3.7
  3. Hibernate 4.2.1

Following jar must be in classpath

  1. antlr-2.7.7.jar
  2. classes12.jar (Oracle Driver)
  3. dom4j-1.6.1.jar
  4. hibernate-commons-annotations-4.0.2.Final.jar
  5. hibernate-core-4.2.2.Final.jar
  6. hibernate-entitymanager-4.2.2.Final.jar
  7. hibernate-jpa-2.0-api-1.0.1.Final.jar
  8. javassist-3.15.0-GA.jar
  9. jboss-logging-3.1.0.GA.jar
  10. jboss-transaction-api_1.1_spec-1.0.1.Final.jar

I am creating a sample project that persists Student object (simple POJO (Plain Old Java Object)) into database using JPA

Firstly create a Java Project (File->New->Project), select Java Project and click next, provide name as "JPA2Example" according to following screenshot

Create JPA Project Java Persistence(JPA) With Hibernate

persistence.xml

persistence.xml file must be under src/META-INF (Please check below screenshot(project structure)

<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" xmlns="http://java.sun.com/xml/ns/persistence">
	<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
		<class>com.test.jpa.Student</class>
		<properties>
			<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver" />
			<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@192.148.27.140:1521:database"/>
			<property name="javax.persistence.jdbc.user" value="username"/>
			<property name="javax.persistence.jdbc.password" value="password"/>
			<property name="hibernate.connection.pool_size" value="1"/>
			<property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect"/>
			<property name="show_sql" value="true"/>
			<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
		</properties>
	</persistence-unit>
</persistence>

Create a Student Object(Student.java)

package com.test.jpa;

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

@Entity
@Table
(name = "STUDENT")
public class Student implements java.io.Serializable {

 
@Id
  @GeneratedValue
(strategy = GenerationType.AUTO)
 
@Column(name = "STUDENTID")
 
private long studentId;
 
@Column(name = "STUDENTNAME")
 
private String studentName;

 
public void setStudentId(long studentId) {
   
this.studentId = studentId;
 
}

 
public long getStudentId() {
   
return studentId;
 
}

 
public void setStudentName(String studentName) {
   
this.studentName = studentName;
 
}

 
public String getStudentName() {
   
return studentName;
 
}

}
@Entity declares the class as an entity (i.e. a persistent POJO class)
@Table is set at the class level; it allows you to define the table, catalog, and schema names for your entity mapping. If no @Table is defined the default values are used: the unqualified class name of the entity.
@Id declares the identifier property of this entity.
@GeneratedValue annotation is used to specify the primary key generation strategy to use. If the strategy is not specified by default AUTO will be used.
@Column annotation is used to specify the details of the column to which a field or property will be mapped. If the @Column annotation is not specified by default the property name will be used as the column name.

EntityManagerUtil.java

package com.test.jpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;


public class EntityManagerUtil {
 
private static final EntityManagerFactory entityManagerFactory;
 
static {
   
try {
     
entityManagerFactory = Persistence.createEntityManagerFactory("test");

   
} catch (Throwable ex) {
     
System.err.println("Initial SessionFactory creation failed." + ex);
     
throw new ExceptionInInitializerError(ex);
   
}
  }

 
public static EntityManager getEntityManager() {
   
return entityManagerFactory.createEntityManager();

 
}
}

Package Structure

Java Persistence(JPA) Tutorial With Hibernate Structure

Testing (JPAExample.java)

package com.test.jpa;

import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;



public class JPAExample {

 
private EntityManager entityManager = EntityManagerUtil.getEntityManager();

 
public static void main(String[] args) {
   
JPAExample example = new JPAExample();
    System.out.println
("After Sucessfully insertion ");
    Student student1 = example.saveStudent
("Sumith");
    Student student2 = example.saveStudent
("Anoop");
    example.listStudent
();
    System.out.println
("After Sucessfully modification ");
    example.updateStudent
(student1.getStudentId(), "Sumith Honai");
    example.updateStudent
(student2.getStudentId(), "Anoop Pavanai");
    example.listStudent
();
    System.out.println
("After Sucessfully deletion ");
    example.deleteStudent
(student2.getStudentId());
    example.listStudent
();
   

 
}

 
public Student saveStudent(String studentName) {
   
Student student = new Student();
   
try {
     
entityManager.getTransaction().begin();
      student.setStudentName
(studentName);
      student = entityManager.merge
(student);
      entityManager.getTransaction
().commit();
   
} catch (Exception e) {
     
entityManager.getTransaction().rollback();
   
}
   
return student;
 
}

 
public void listStudent() {
   
try {
     
entityManager.getTransaction().begin();
     
@SuppressWarnings("unchecked")
     
List<Student> Students = entityManager.createQuery("from Student").getResultList();
     
for (Iterator<Student> iterator = Students.iterator(); iterator.hasNext();) {
       
Student student = (Student) iterator.next();
        System.out.println
(student.getStudentName());
     
}
     
entityManager.getTransaction().commit();
   
} catch (Exception e) {
     
entityManager.getTransaction().rollback();
   
}
  }

 
public void updateStudent(Long studentId, String studentName) {
   
try {
     
entityManager.getTransaction().begin();
      Student student =
(Student) entityManager.find(Student.class, studentId);
      student.setStudentName
(studentName);
      entityManager.getTransaction
().commit();
   
} catch (Exception e) {
     
entityManager.getTransaction().rollback();
   
}
  }

 
public void deleteStudent(Long studentId) {
   
try {
     
entityManager.getTransaction().begin();
      Student student =
(Student) entityManager.find(Student.class, studentId);
      entityManager.remove
(student);
      entityManager.getTransaction
().commit();
   
} catch (Exception e) {
     
entityManager.getTransaction().rollback();
   
}
  }
}

Output

After Sucessfully insertion 
Sumith
Anoop
After Sucessfully modification 
Sumith Honai
Anoop Pavanai
After Sucessfully deletion 
Sumith Honai

 









4 Responses to "Java Persistence (JPA) Tutorial With Hibernate"
  1. Audwit 2012-12-01 09:33:18.0
  1. admin 2012-12-02 09:33:18.0
  1. Prateek 2012-12-03 09:33:18.0
  1. admin 2012-12-04 09:33:18.0

Your email address will not be published. Required fields are marked *