What is Java persistence API (JPA)

Hello Solvers………..

In this blog I have discussed about what is JPA and how to implement demo project to understand this principle.

In the IT world we work with many number of data. So these data is subject to various processes, so for these processes we use various of software or tools.

Sometimes data might be loss. Because of that we should persist our data in a secure place like a database or files.

Most of the database are relational database that’s mean if we want to save data in a database we should create tables and save those data. But in java we work with objects. That’s mean in java most of data behaving as objects. So we have a problem here what databases have a tables with rows and columns but java application use objects, so how these objects save in a database.

To solve this problem, we have ORM (object relational mapping) concept. If you have class and there are some variables, So when we save data in a database, ORM convert that objects in to the normal data and then save in the database, and also when we want to retrieve data into the application from a database we need to convert data in to the objects because java deal with objects, So ORM convert data in to objects. This concept we can use with different technologies like java, .Net.

You can understand how ORM is work from below image.

When we use ORM in java we should have a tool, so there are several tools like Hibernet, iBaties, TopLink. Sometimes we have to switch between these different tools. But it’s not easier because these tools are working independently. To solve this problem, we should have a common structure. To solve this problem there has been introduced a solution. That is JPA, It’s basically specification. All these tools are implement this JPA standard, because of that we can switch easily between different tools.

……………………………………………………………………………………….

Let’s move into the implementation part, so after this implementation you can understand how JPA actually work in a real project.

First we want to create simple maven project. You can use any IDE like Intellij IDEA, Eclipse. In here I have used Intellij IDEA. So then you can create simple maven quickstart project.

Then you want a database because we deal with database in this implement. So you can use any DBMS tool like MYSQL workbench, postgresql. I have used MYSQL workbench.

And then you can create a database with any name, my database name is student_details and also I have crated one table called stu_subject in that table has stored.

Then we need to create a class which represent a table of the database. So in here I have created a class called stu_subject, remember you should be named the class with your database table’s name that you have created.

Then we need to mention properties in the class that we have created. These properties include in the database table. So my table has 4 properties then I have created 4 properties and then we should generate getters and setters because normally we create properties as private. And also I have generated toString method also because we want to print values of objects.

package com.DevSolver;

import javax.persistence.Entity;
import javax.persistence.Id;

//Convert class into an entity by this annotation
@Entity
public class stu_subject {

//This annotation represent what is the primary key
@Id
private int id;
private String stu_name;
private String subject;
private String grade;


public int getId() {
return id;
}

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

public String getStu_name() {
return stu_name;
}

public void setStu_name(String stu_name) {
this.stu_name = stu_name;
}

public String getSubject() {
return subject;
}

public void setSubject(String subject) {
this.subject = subject;
}

public String getGrade() {
return grade;
}

public void setGrade(String grade) {
this.grade = grade;
}

@Override
public String toString() {
return "stu_subject{" +
"id=" + id +
", stu_name='" + stu_name + '\'' +
", subject='" + subject + '\'' +
", grade='" + grade + '\'' +
'}';
}
}

Then we need to add hibernate dependency, when we add this dependency to our project then automatically download all the jar files that we need so we don’t need to download one by one.

You can go to the mavenrepository.com and then search hibernate ORM functionality then you can select any version, then you can copy the dependency. Then you can paste that in to the dependencies section under pom.xml file. Now automatically download will start. We should have one more dependency that is msql connector. This also you can add same as before.

Then what we have to do. We should specify the which DBMS work with, username, password. So that we should create a configuration file. In here I have crated a folder called resources and under that I have created another folder called META-INF. In this META-INF folder, I have created my config file named as percistance.xml.

<?xml version="1.0" encoding="UTF-8" ?>

<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistance_2_1.xsd">
<persistence-unit name="pu">

<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/student_details"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root123"/>
</properties>

</persistence-unit>

</persistence>

This is my config file, your file might change because this file depend on your database details like username, password, database url.

Then we create two objects in app.java main class. We create this object from EntityManagerFactory and EntityManager, because the model class that we created in before it’s like an entity. We should manage them, for that we need an entity manager.

package com.DevSolver;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class App
{
public static void main( String[] args )
{
//In here I save some values to the database.
stu_subject ss = new stu_subject();
ss.setId(4);
ss.setStu_name("Namal");
ss.setSubject("Data structures and algorithm");
ss.setGrade("A");

//We have to create a link with persistence.xml file. This "pu" persistence unit name.
EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu");
EntityManager em = emf.createEntityManager();

//Before save above data we should start a transaction and after we should commit.
em.getTransaction().begin();
em.persist(ss);
em.getTransaction().commit();

//In here i fetch values from the database
stu_subject sd = em.find(stu_subject.class, 3);
System.out.println(sd);

}
}

So our demo program’s implementation is done. Let’s check the result.

Yes, we have a right output. Here we have the data that include in id number 3. So then we check whether our data sent or not into the database.

Yes, its pass. Data is stored related to Id number 4.

So you can understand the power of the JPA. We can store and retrieve data very easily.

!!!!!!!!!!!!

Undergraduate at university of Kelaniya, and Studies ICT in faculty of computing and technology.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store