Skip to main content
Java API

Introduction to Java Persistence API (JPA)

Understanding JPA

JPA (Java Persistence API) is an open source software, developed by Oracle Corporation. JPA totally depends on providers and vendors such as Hibernate, Eclipse link, Top link, iBATIS etc.

JPA has a set method which does not require implementation as it is actually an interface.  It is a specification for accessing, persisting and managing the data between Java objects and the relational DB. JPA specifies the set of rules and guidelines for developing the interfaces .

JPA  has its own configuration file named,  Persistence.xml. Persistence files should be have a unique name and be located inside the resource folder (like META-INF/Persistence.xml).

Some notes:

  1. JPA is part of EJB specification which is released in Java 1.5v.
  2. Cache features are not available so performance is not great.
  3. It does not other languages such as DotNet.
  4. It generates JPQL(Java Persistence Query Language)
  5. We cannot use JPA directly.

Why JPA?

JPA is the standard and standards are always good for application implementation. A standard persistence API is very convenient from a client point of view, making it relatively easy to switch one implementation with  another such as ORMs like Hibernate, Eclipse link, Top link, iBATIS.

JPA can automatically  handle open and close sessions and connection, too.  Therefore it reduces code to manage sessions or connection by programmers or developers.

Where is JPA used in an application?

It is used to reduce the burden of writing codes for relational object management(ORM) and a programmer follows the ‘JPA Provider’ framework, which allows easy interaction with database instance (Entity with DAO implementation). Here the required framework is taken over by JPA.

HTML, JSP (Presentation Layer) – Entities (Business Logic) – ORM.xml and JPA Providers (JPA Layer) - DAO (Database Layer).

JPA relationship hierarchy between objects:

JPA Application

Getting further into hierarchy units:

  1. Entity Manager Factory: This object follows the factory class and it creates or manages multiple Entity Manager instances(As per hierarchy).
  2. Entity Manager: This object contains the methods.
  3. Entity: This object can create both abstract and concrete classes.
  4. Entity Transaction: This object  has one-to-one relationship with Entity Manager.
  5. Persistence: Persistence is a class.This class contains the static methods to get Entity Manager Factory instance.
  6. Query: Query is a interface.This interface is implemented by each JPA vendor.

Relationship between entity classes:  Create a Java project called “com.trigent.jpa”, create again a folder “lib” and  add the required JPA ,Hibernate jars and mysql.jar into this folder.

 

package com.trigent.jpa;

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

@Entity
@Table(name = "EMP_DB")
 public class Employee {
    @Id
    @Column(name = "id")
    private int id;
    @Column(name = "fullName")
    private String fullName;
    @Column(name = "dept")
    private String dept;
    public Employee() {
       }

    public Employee(int id, String fullName, String dept) {
        this.setId(id);
        this.setFullName(fullName);
        this.setDept(dept);
    }
    public int getId() {
    return id;
    }
    public void setId(int id) {
    this.id = id;
    }
    public String getFullName() {
    return fullName;
    }
    public void setFullName(String fullName) {
    this.fullName = fullName;
    }
    public String getDept() {
    return dept;
    }
    public void setDept(String dept) {
    this.dept = dept;
    }
}

Persistence.xml:

Create  the file “persistence.xml”. This example uses Hibernate specific  via the data source describing the database properties which are used for connection. In the parameter “hibernate.hbm2ddl.auto” you specify that the database scheme will be automatically dropped and created. The database specified via “javax.persistence.jdbc.url” will be automatically created by the MySql Driver. This is an option to setting the  log category org.hibernate.SQL to debug. The class-name of a Hibernate  org.hibernate.dialect.Dialect which allows Hibernate to generate SQL for a particular relational DB.

<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="TrigentEmployee" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
      <class>com.trigent.jpa.Employee</class>
       <properties>
         <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/>
         <property name="javax.persistence.jdbc.user" value="root"/>
         <property name="javax.persistence.jdbc.password" value="admin"/>
         <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
          <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
          <property name="hibernate.hbm2ddl.auto" value="create-update" />
          <property name="hibernate.show_sql" value="true" />
      </properties>
    </persistence-unit>
</persistence>

And below is a test class:

package com.trigent.jpa;

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

public class JpaTest {
private static EntityManager em;

public static void main(String[] args) {

EntityManagerFactory emf = Persistence.createEntityManagerFactory("TrigentEmployee");
    em = emf.createEntityManager();
    createEmployee(1, "Monu Rawat", "IT Programmer");
    createEmployee(2, "Vineet Kumar", "IT Programmer");
    createEmployee(3, "Rajesh Khanna", "IT Lead Programmer");

}

private static void createEmployee(int id, String fullName, String dept) {
        em.getTransaction().begin();
        Employee emp = new Employee(id, fullName, dept);
        em.persist(emp);
        em.getTransaction().commit();
    }
}
 

 

 

Monu Kumar

Monu Kumar

Monu Kumar works as Software Engineer with Trigent Software. He has nearly five years of experience in Java/J2ee technology. He also has strong experience in Core Java , Apache OFBIZ, JSP, Spring MVC, Struts, Hibernate with JPA, JQuery/Java script,MYSQL, POSTGRESQL and so forth

4 thoughts on “Introduction to Java Persistence API (JPA)

  1. Great items from you, man. I’ve keep in mind your stuff previous to and you’re just too fantastic. I really like what you have bought right here, really like what you are saying and the way in which you are saying it. You are making it enjoyable and you still take care of to keep it wise. I can not wait to learn far more from you. That is actually a wonderful web site.|

Leave a Reply

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

3 + two =