Java ProgrammingLearn How to use Java Persistence API

Learn How to use Java Persistence API

java-persistence-api

The JPA, or the Java Persistence API, is a special specification which defines how different Java objects or classes access and interact with the data in a Java database. It is one of the many approaches to ORM (Object to Relational Mapping), but is now accepted as the most standard approach in Java. The term ORM actually refers to the process of mapping, which can be either done with the Java objects, or with database tables. JPA cannot be used on its own, as it is simply a Java specification. To actually use these specifications or interfaces, a proper implementation must be done. There are many different implementations which are free and open-source.

JPA also needs a Java database in order to map the objects. JPA can persist and map a large variety of objects, including Plain Old Java Objects (POJO). It doesn’t even need any particular method or interface for different classes of objects, unlike its predecessor EJB 2 CMP, which required additional methods for object classes. Using JPA, the mappings of objects are easily defined either by simple annotations, or by creating an entity using XML. This allows the object to be properly mapped in relation to the database. JPA even has different APIs for these definitions, like the EntityManager API for managing XML entities, which are queries running alongside the database. JPL also has a special query language for querying the objects.

Why we need JPA?
There are many different types of approaches available to the user for mapping Java objects in relational databases, for example JDO, EJB 2 (the predecessor of JPA), object databases and of course, serialisation. So, why do we need another such API at all? This is because most of these frameworks have many different problems. JPA, on the other hand, is made by adopting all the advantages of these specifications and merging them to a separate API which doesn’t require any of them. Some of the disadvantages of these APIs are given below.

  • JDO: Java Data Objects is considered as one of the best tools for object mapping. It has nearly all the features that JPA has, and is also very easy to use. However, it lacks a very important feature of JPA, i.e. it supports only non-relational databases, which renders many of its potential usages obsolete. On the other hand, JPA supports both relational and non-relational databases.
  • EJB 2: EJB, or Enterprise Java Beans, was introduced in the Enterprise editions of Java. It has a lot of features, including features of standard ORMs and non-relational systems. However, many advanced features are lacking in this specification. Also, expensive servers are required to run the resource-hogging codes of this specification.
  • Serialisation: This is the built-in function of Java which allows the transformation of objects into data. This is an extremely easy to use function. However, it also lacks many features of third party specifications. It cannot handle large amounts of data as it needs to store the entire object graph even while working on a single part of the graph. Also, it lacks data integrity as it cannot undo changes made while updating. Another major limitation of this framework is when many different threads are accessing the data on the server, they conflict with each other, harming the system stability. Thus, serialisation has very limited use in application development.

JPA adopts and even builds upon all these features of different specifications, and also negates their limitations. It is compatible with different types of databases, has a lot of security options, promotes data integrity and has implementations which support both enterprise editions and standard editions of Java.

Implementing JPA – What are the components?
There are many different components of JPA. In object relational mapping, the main part is the mapping orm.xml file. ORM allows the conversion of data type from object to relational or the converse. It binds the data for an object to the object itself.

ORM consists of the interaction of three phases. The first phase, also called the Object data phase, has many different types of classes and service interfaces. It consists of the main business logics and components.

The second phase is known as the persistence phase where the main components interacting are Object Grid, orm.xml mapping file and the main JPA provider.

In the third phase, or the relational phase, the mapped data is systematically connected to the business layer, where it is stored in the cache memory. After the business layer confirms the data, it is attached to the database.

Basic JPA architecture
The architecture of the JPA consists of different components like EntityManagerFactory, EntityManager, Entity objects, orm.xml file and persistence units. The JPA architecture is based completely upon the Java programming framework, which includes both the EE and SE environments of Java. Also, the architecture includes a query language known as Java Persistence Query Language (JPQL).

Some of the components are given below: –

  • EntityManagerFactory: This component is very important as it creates the instances of EntityManager. Before the shutdown of the application, the EntityManagerFactory must also be closed in order to prevent the creation of entities. After it is terminated, all the EntityManager processes from it are declared closed. It creates EntityManager processes in the context of the persistence units.
  • EntityManager: This component actually does the work of managing entities. Also, it interacts with the entities either by creating, updating or by destroying them. Further, multiple instances of this API can be created by EntityManagerFactory.
  • Entity: These objects are the records actually stored in the database.
  • EntityTransaction: This is the class which actually manages the work done by the EntityManager.
  • Persistence: This class allows the creation of the EntityManagerFactory instances by providing the methods for its deployment
  • Query: Another JPA vendor supports this class for obtaining the relational data of objects.

Environment setup:
To configure the environment here are the steps that need to be followed:

Now your environment is ready to write JPA classes in Java. In the next section, we will create some sample applications.

Sample application: –
In this example, we will create a sample JPA application in Eclipse IDE. First create a JPA project as shown in the screen shot below.
jpa-project
Image1: Create JPA project
Now, Download the Eclipselink shown in the screen shot below. This is required for the JPA APIs in the project.
download-library
Image2: Select download version
eclipselink-download
Image3: EclipseLink download

Following is the project structure in the Eclipse IDE.
project-structure
Image4: Project structure

Now, let us check the code components.

Listing 1: – This is the class to create an Employee object

[code]
package eduonix.jpa.com;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import eduonix.jpa.com.EmpObj;
public class CreateEmpObj {
public static void main(String[] args) {
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("JPADemoApp");
EntityManager entitymanager = emfactory.createEntityManager();
entitymanager.getTransaction().begin();
EmpObj empobj = new EmpObj();
empobj.setEmpid(111);
empobj.setEmpname("Kaushik");
empobj.setEmpsal(30000);
empobj.setEmpdeg("Engineer");
entitymanager.persist(empobj);
entitymanager.getTransaction().commit();
entitymanager.close();
emfactory.close();
}
}
[/code]

Listing 2: – This is the class to update an Employee object.

[code]
package eduonix.jpa.com;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import eduonix.jpa.com.EmpObj;
public class UpdateEmpObj {
public static void main(String[] args) {
EntityManagerFactory emfactory = Persistence
.createEntityManagerFactory("Eclipselink_JPA");
EntityManager entitymanager = emfactory.createEntityManager();
entitymanager.getTransaction().begin();
EmpObj EmpObj = entitymanager.find(EmpObj.class, 101);
// before updating
System.out.println(EmpObj);
EmpObj.setEmpsal(45000);
entitymanager.getTransaction().commit();
// after updating
System.out.println(EmpObj);
entitymanager.close();
emfactory.close();
}
}
[/code]

Listing 3: – This is the Employee object class

[code]
package eduonix.jpa.com;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class EmpObj {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int empid;
private String empname;
private double empsal;
private String empdeg;
public EmpObj(int empid, String empname, double empsal, String empdeg) {
super();
this.empid = empid;
this.empname = empname;
this.empsal = empsal;
this.empdeg = empdeg;
}
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public double getEmpsal() {
return empsal;
}
public void setEmpsal(double empsal) {
this.empsal = empsal;
}
public String getEmpdeg() {
return empdeg;
}
public void setEmpdeg(String empdeg) {
this.empdeg = empdeg;
}
public EmpObj() {
super();
}
@Override
public String toString() {
return "EmpObjee [Id=" + empid + ", Name=" + empname + ", Salary=" + empsal
+ ", deg=" + empdeg + "]";
}
}
[/code]

Listing 4: – This is the persistence XML for mapping

[code]
<?xml version="1.0" encoding="UTF-8"?>
<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="JPADemoApp" transaction-type="RESOURCE_LOCAL">
<class>eduonix.jpa.com.EmpObj</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="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
[/code]

First execute the CreateEmpObj.Java class to create the employee object. After this, execute the UpdateEmpObj.Java class and it will first print the original values and then show the updated values.

Output before updating:
Id : 111
Name: Kaushik
Salary: 30000
Deg: Engineer

Output after updating:
Id : 111
Name: Kaushik
Salary: 45000
Deg: Engineer

Conclusion:
JPA is one of the best APIs for Java development. While there are many approaches to persistence programming, this one is considered as the best by most of the developers due to its great reliability and improvements offered over other specifications. The implementation part is also easier to learn. In this tutorial, we have tried to explain all the details in simple steps. Hope it will help the developers to implement JPA easily.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -