JPA

Ashmeet Kaur
9 min readApr 2, 2023

--

JPA is nothing but Java Persistent API/Interface.For Example It has defined some Operation and functions which can be done on DB.
Hibernate is Implemention of JPA.It is anologus to class and JPA is anologus to Interface .Interacting with the database will be done at the hibernate level.JPA and Hibernate are both used for Mysq Databases.

To understand please see the diagram

Diffrence between JPA and Hibernate
How JPA Interact

A user is interact with JPA which is a Entity.Internally JpA interact with diffrent entities.We have to use the entity Hibernate and JDBC for using JPA.

One Point to Note here is that for Relational DBs we need the hibernate as well as driver .but for non sql one we only need Driver .In Nosql databases,there is no framework like Hibernate because they are non structured.

Firstly we are going to see how can we include hibernate in our project

Creating project

The dependencis that we included in our project is
✔️Spring Web- This is for the interaction with the API.
✔️Mysql Driver-This is use for mysql connectivity.
✔️Lombok-We are using this for writing cleaner and better code.
✔️Spring Data JPA-We are using this for Hibernate.

We are using Java 8 and Maven as build tool.

If we understand ,the main working of hibernate is to map java object to table .
Lets understand this through this example

public class Person {
private Integer id ;
private String firstname;
private String lastname;
private String dob;
private Integer age;

}

We have this class here , we want to map Person Class to the table present in the Database .But How will hibernate know that it has to map only this Person Class and not some other class .For this we will be using @Entity

We know that our JPA is a interface right .It can be implements via different frameworks like hibernate,OpenJPa and many more .

Lets understand it more basically.How this Entity is there .

---------------------------Snippet 1------------------------------------------
package jakarta.persistence;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Entity {
String name() default "";
}

@Entity is coming from jakarta.persistence.Lets see the dependency tree here .

This @Entity is present in jakarta.persistence library.

Open the terminal

mvn dependency:tree

We will get the dependency.

We can see that the dependency is coming from the jpa .So actually JPA is doing the mapping .(see jakarta.persistence in 3rd line).

So here now the question arises why this is javax.persistence is present in jpa and not under hibernate ?
So that any orm or framework can map our java class to the database.Lets undersatnd better .There can be many orm tools which might be impelementing the Jpa for example-Hibernate,OpenJpa,Elips and many more.But in our project we are using here hibernate.

So Basically we want to map any model class to sql databases.What we hibernate do here .He will be converting the java class to the hibernate table.We will be using @Entity in the classes.and Jpa will scan all the classes and hibernate will create table where the class is having Unnamed Entity

@Entity//Entity is getting used to map it the table
public class Person{
private Integer id ;
private String firstname;
private String lastname;
private String dob;
private Integer age;

}

Suppose if we want to keep the column name as first_name.Then we will use the annotation as @coloum .

@Column(name = "first_name")
private String firstname;

If we want to change the table name we can write it as

@Table(name = "person")
public class Person{
private Integer id ;
@Column(name = "first_name")
private String firstname;
private String lastname;
private String dob;
private Integer age;

}

Suppose if you dont want to map to a table then, u can use static keyword.

@Table(name = "person")
public class Person{
private static int counter;
private Integer id ;
@Column(name = "first_name")
private String firstname;
private String lastname;
private String dob;
private Integer age;

}

There are three types of object in Hibernate
a)Transient
b)Persistent.
c).Detached objects.

Transient means you have created a person object but that person object is not mapped to any row.

Before understanding this ,Lets understand the internal working of Hibernate .

We have this table

Table person

We have this table where row is A,B,C,D,E.Lets See that the table name is person here .

Now we have this class

public class Person
{
int A;
int B;
int C;
int D;
int E;
}

So if we create the object of the person class.

Person p=new Person();
p.A=1;
p.B=2;
p.C=3;
p.D=4;
p.E=5;

This object will map to a record in the table .

How mapping in a Hibernate is done?
Hibernate internally has a session service.Hibernate interact with the database using sessions.The data which hibernate is stored in the db will be marked as persistence.Persistent objects are those which are there in the hibernate table.Suppose we have session from 11:00 am to 11:59am.in this hour ,whatever data that has been saved or retrieved from the database is called persistent object.

Suppose we have just created a object Person p1=new Person() and it is not saved and retrieved in the database.Then it is a transient object.

Suppose the session was there from 11:00 till 11:59 then ,till this time only we have retrieved the object but at 12:00 it became detachable object.

📌Although we dont need to make a primary key in a table.But hibernate need primary key for mapping.Its not a database restriction but its a hibernate restriction.@Id will make this a primary key .

    @Id // its should be javax.persistence and now it will considered id.
private Integer id ;

@Transient will make remove this mapping.

@Transient
private String dob;

How are we going to save the object into database ?

👉🏻Lets first extend JpaRepository and since we want to save the Person where primary is of type Integer.


public interface PersonRepository extends JpaRepository<Person,Integer> {
}

Lets see this .Here we can see that id is primary.

@Table(name = "person")
public class Person{
private static int counter;
@Id
private Integer id ;
@Column(name = "first_name")
private String firstname;
private String lastname;
private String dob;
private Integer age;
@Transient
public String dummmy;

}

Why do we need both JPA and hibernate if most of the work is done by JPA ?
Suppose we want to retrive some data .and retrieve consist of multiple parts
🔶To get the Hibernate session- Hibernate returned the session to JPA.
🔶Adding the Query-This does not require hibernate support.
🔶Executing the Query-Hibernate deligate the work to database an database returns it to Hibernate and now these result will be returned back to client by having intermediary in JPA.

📌We use the transient keywords in that case when we dont want to store something in the db as it can be a security concern .

private transient String key;

Lets see the diagram here .We know that JPA is common term for replament with no sql databases.

Hierarchy

For mongo db or cassandra , just include one dependency ,now we will see that simple mongo repository and cassandra repository will be extending this Crud Repository.

Lets see how can we add details to our database.

public void createPerson(CreatePersonRequest personRequest){

Person person=personRequest.to();

👉🏻👉🏻👉🏻👉🏻Person personFromDB=personRepository.save(person);

}

In above line .save will pass the value to the database .

For Retrieving

public  Person getPerson(int id)
{
👉🏻👉🏻👉🏻👉🏻Person person=personRepository.findById(id).get();
return person;

}

The above statement will find the id .but it should be primary field.

One thing to notice here that when we were establishing the db connection manually initially but now in hibernate ,We just have to add db connection in application.properties file.

spring.datasource.url=jdbc:mysql://locahost:3306/jdbl_33person
spring.datasource.username=root
spring.datasource.password=password

Suppose if we give wrong database name .

What is a Hikari Pool ?
It is a pool that is used by hibernate to communicate with the underlying database.So can we do something like if the hikari pool is not there then it will try to create database on its own.Lets see how

spring.datasource.url=jdbc:mysql://locahost:3306/jdl_33jpa?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=password

In the first statement , the hikari will connect with the db if it is present .Else it will create db and connect.Make sure that whichever user you are passing here should have access to create a database.Here our user is root.

+--------------------+
| Database |
+--------------------+
| ashdb |
| information_schema |
| jdbl_33person |
| jdl_33jpa |
| mysql |
| performance_schema |
| sys |
+--------------------+

Now jdl_33jpa successfully created.But table has not been created .let see why?

Trying to insert into Table

We are getting error while trying to insert into table .Why is it so ?

org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.example.demojpa.models.Person
at

We are getting the above error ,lets see why we are getting this error.
Before that ,There are two type of commands
a).DML-create table,create Database,alter ,create index.
b).DDL -insert ,update ,delete.

DDL basically means how you want your schema to behave.

so coming back to the point .
We have to add

spring.jpa.hibernate.ddl-auto=

if it is none ,then we cannot perform any ddl commands over here .
Do Ctrl+shift+F.
we can see

 "name": "spring.jpa.hibernate.ddl-auto",
"values": [
{
"value": "none",
"description": "Disable DDL handling."
},
{
"value": "validate",
"description": "Validate the schema, make no changes to the database."
},
{
"value": "update",
"description": "Update the schema if necessary."
},
{
"value": "create",
"description": "Create the schema and destroy previous data."
},
{
"value": "create-drop",
"description": "Create and then destroy the schema at the end of the session."
}
]
},

From the above snippet we understood that we cannot keep it none ,Hence we have to keep it either from the below value.But we cannot use “validation” here because we are not having table here .

Lets see the diffrence between update,create and create-drop
a).Update -It will create if table does not exist.table exist.It will update only if the It will never delete the table,index or data .
b)Create-Here whenever we restart the application, the previous data wil be lost.
c) Create-drop-Here whenever we stop the application, the previous data will be lost.

lets see this .
In application.properties file we have

spring.datasource.url=jdbc:mysql://localhost:3306/jdl_33jpa?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=create
Hibernate: drop table if exists author
Hibernate: drop table if exists person
Hibernate: create table author (id integer not null, name varchar(255), primary key (id)) engine=InnoDB
Hibernate: create table person (id integer not null, age integer, dob varchar(255), first_name varchar(255), lastname varchar(255), primary key (id)) engine=InnoDB

Two tables has been created

    
+---------------------+
| Tables_in_jdl_33jpa |
+---------------------+
| author |
| person |
+---------------------+
2 rows in set (0.02 sec)
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| id | int | NO | PRI | NULL | |
| age | int | YES | | NULL | |
| dob | varchar(255) | YES | | NULL | |
| first_name | varchar(30) | YES | | NULL | |
| last_name | varchar(255) | YES | | NULL | |
+------------+--------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

Here the lastName we have as camel case but hibernate while adding makes it last_name.

📌It is important to use update because the servers keep on starting .

please see the below attached github link for refernce

https://github.com/ashmeet4491/SpringBootHibernate

#JPA
#Hiberate
#Database Connectivity
#Core Java

--

--