0% found this document useful (0 votes)
222 views

JPA

JPA (Java Persistence API) is a specification that allows Java developers to map Java objects to relational databases in a standard way. It provides an object-relational mapping (ORM) layer that acts as a bridge between object-oriented domain models and relational databases. JPA implementations like Hibernate and EclipseLink allow developers to work directly with Java objects instead of using SQL statements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
222 views

JPA

JPA (Java Persistence API) is a specification that allows Java developers to map Java objects to relational databases in a standard way. It provides an object-relational mapping (ORM) layer that acts as a bridge between object-oriented domain models and relational databases. JPA implementations like Hibernate and EclipseLink allow developers to work directly with Java objects instead of using SQL statements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

From javatpoint.

com
-------------------
1) What is JPA ?
-----------------
JPA stands for Java Persistence API.
It is used to persist data between Java object and relational database.
JPA acts as a bridge between object-oriented domain models and relational database
systems.
It is a specification which gives standards to the ORM tools.
All the ORM tools such as Hibernate, iBatis, Top Link etc follows the rules or
specifications given by the JPA.
It provides a platform to work directly with objects insted of using SQL
statements.
It provides Object-relational mapping to manage relational data in Java
applications.

As JPA is just a specification, it doesn't perform any operation by itself. It


requires an implementation.
So, ORM tools like Hibernate, TopLink and iBatis implements JPA specifications for
data persistence.
Current version is JPA2.2 released in 2017

2) Object Relational Mapping(ORM)


---------------------------------
Object Relational Mapping is a functionality which is used to develop and maintain
a relationship between object and relational database
by mapping an object state to database column.

Java-----------------ORM----------------Database
(Object) (Column)

3) ORM Frameworks
------------------
Hibernate, iBatis, TopLink etc.

4) Mapping directions
---------------------

Unidirectional:
In this relationship, only one entity can refer the properties to another entity.
Only one entity has a relationship field to the other entity.
Ex: either parent to child or child to parent communication is possible.

Bidirectional:
In this relationship, every entity can refer the properties to another entity.
Both the entities has relationship fields to the other entities.
Ex: Both parent to child and child to parent communication is possible.

5) Types of Mappings
--------------------
One-to-one: Here, instance of each entity is related to a single instance of
another entity.
One-to-many: In this relationship, an instance of one entity can be related to more
than one instance of another entity.
Many-to-one: In this relationship, multiple instances of an entity can be related
to single instance of another entity.
Many-to-many: Here, multiple instances of an entity can be related to multiple
instances of another entity.
6) Simple entity class
-----------------------
import javax.persistence.*;
@Entity //To make Java class as an Entity class
public class Student {
@Id //To mark a field as primary key column
private int id;
private String name;
private long fees;
public Student() {} // No-args constructor
public Student(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
//Remaining getters and setters
}

7) JPA Entity Manager


----------------------
Entity Manager is used to perform DB operations like Create, Read, Update, Delete
etc operations.
Entity objects will be managed by using Entity Manager.

8) Steps to persist an entity object


------------------------------------
a) Creating an entity manager factory object
EntityManagerFactory emf=Persistence.createEntityManagerFactory("Student_details");

EntityManagerFactory - Interface present in java.persistence package is used to


provide an entity manager.
Persistence - The Persistence is a bootstrap class which is used to obtain an
EntityManagerFactory interface.
createEntityManagerFactory() method - The role of this method is to create and
return an EntityManagerFactory for the named persistence unit.
Thus, this method contains the name of persistence unit passed in the
Persistence.xml file.

b) Obtaining an entity manager from factory.

EntityManager em=emf.createEntityManager();
EntityManager - An EntityManager is an interface
createEntityManager() method - It creates new application-managed EntityManager

c) Intializing an entity manager.

em.getTransaction().begin();
getTransaction() method - This method returns the resource-level EntityTransaction
object.
begin() method - This method is used to start the transaction.
d) Persisting a data into relational database.

em.persist(s1);
persist() - This method is used to make an instance managed and persistent. An
entity instance is passed within this method.

e) Closing the transaction

em.getTransaction().commit();

f) Releasing the factory resources.

emf.close();
em.close();
close() - This method is used to releasing the factory resources.

9) Inserting an entity
-----------------------
In JPA, we can easily insert data into database through entities. The EntityManager
provides persist() method to insert records.

a) StudentEntity.java

package com.javatpoint.jpa.student;
import javax.persistence.*;

@Entity
@Table(name="student")
public class StudentEntity {

@Id
private int s_id;
private String s_name;
private int s_age;

public StudentEntity(int s_id, String s_name, int s_age) {


super();
this.s_id = s_id;
this.s_name = s_name;
this.s_age = s_age;
}

public StudentEntity() {
super();
}

public int getS_id() {


return s_id;
}

public void setS_id(int s_id) {


this.s_id = s_id;
}
//Remaining setters and getters
}

Now, map the entity class and other databases confiuguration in Persistence.xml
file.
b) Persistence.xml
<persistence>
<persistence-unit name="Student_details">

<class>com.javatpoint.jpa.student.StudentEntity</class>

<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/studentdata"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="eclipselink.logging.level" value="SEVERE"/>
<property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
</properties>

</persistence-unit>
</persistence>

Create a persistence class named as PersistStudent.java under


com.javatpoint.jpa.persist package to persist the entity object with data.

c) PersistStudent.java

package com.javatpoint.jpa.persist;

import com.javatpoint.jpa.student.*;
import javax.persistence.*;
public class PersistStudent {

public static void main(String args[])


{

EntityManagerFactory
emf=Persistence.createEntityManagerFactory("Student_details");
EntityManager em=emf.createEntityManager();

em.getTransaction().begin();

StudentEntity s1=new StudentEntity();


s1.setS_id(101);
s1.setS_name("Gaurav");
s1.setS_age(24);
//Can create other student objects s2,s3 etc

em.persist(s1);
em.persist(s2);
em.persist(s3);

em.getTransaction().commit();

emf.close();
em.close();

}
}

10) Finding an entity


---------------------
To find an entity, EntityManger interface provides find() method that searches an
element on the basis of primary key.
//Transaction is not required to perform read operation
StudentEntity s=em.find(StudentEntity.class,101);

11) Update an Entity


---------------------
We will update an entity on the basis of primary key.
StudentEntity s=em.find(StudentEntity.class,102);
s.setS_age(30);

12) Deleting an Entity


-----------------------
To delete a record from database, EntityManager interface provides remove() method.
The remove() method uses primary key to delete the particular record.
//Transacion required
StudentEntity s=em.find(StudentEntity.class,102);
em.remove(s);

13) List Mapping Example


--------------------------
In this example, we embed an object in an entity class and define it as a
collection type List.

private List<Address> address=new ArrayList<Address>();

a) Employee.java

package com.javatpoint.jpa;
import java.util.*;

import javax.persistence.*;
@Entity

public class Employee {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int e_id;
private String e_name;

@ElementCollection // to store multiple child entities


private List<Address> address=new ArrayList<Address>();

//Remaining setters and getters

public List<Address> getAddress() {


return address;
}

public void setAddress(List<Address> address) {


this.address = address;
}

b) Address.java
package com.javatpoint.jpa;
import javax.persistence.*;

@Embeddable
public class Address {

private int e_pincode;


private String e_city;
private String e_state;
//setters and getters

c) Persistence.xml

<persistence>
<persistence-unit name="Collection_Type">

<class>com.javatpoint.jpa.Employee</class>
<class>com.javatpoint.jpa.Address</class>

<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/collection_mapping"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="eclipselink.logging.level" value="SEVERE"/>
<property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
</properties>

</persistence-unit>
</persistence>

d) ListMapping.java

package com.javatpoint.collection;
import javax.persistence.*;
import com.javatpoint.jpa.*;
public class ListMapping{

public static void main(String[] args) {

EntityManagerFactory
emf=Persistence.createEntityManagerFactory("Collection_Type");
EntityManager em=emf.createEntityManager();

em.getTransaction().begin();

Address a1=new Address();


a1.setE_pincode(201301);
a1.setE_city("Noida");
a1.setE_state("Uttar Pradesh");

Address a2=new Address();


a2.setE_pincode(302001);
a2.setE_city("Jaipur");
a2.setE_state("Rajasthan");

Employee e1=new Employee();


e1.setE_id(1);
e1.setE_name("Vijay");
e1.getAddress().add(a1);

Employee e2=new Employee();


e2.setE_id(2);
e2.setE_name("John");
e2.getAddress().add(a2);

em.persist(e1);
em.persist(e2);

em.getTransaction().commit();

em.close();
emf.close();

14) Set Mapping and Map Mapping


-------------------------------
Also same as List Mapping

15) One-To-One Mapping


-----------------------
In this type of association one instance of source entity can be mapped atmost one
instance of target entity.
In this example, we will create a One-To-One relationship between a Student and
Library in such a way that one student can be issued only one type of book.

a) Student.java

package com.javatpoint.mapping;

import javax.persistence.*;

@Entity
public class Student {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int s_id;
private String s_name;
//setters and getters

b) Library.java
package com.javatpoint.mapping;
import javax.persistence.*;

@Entity
public class Library {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int b_id;
private String b_name;

@OneToOne
private Student stud;

public Library(int b_id, String b_name, Student stud) {


super();
this.b_id = b_id;
this.b_name = b_name;
this.stud = stud;
}

public Library() {
super();

}
//setters and getters
}

c) Persistence.xml

<persistence>
<persistence-unit name="Book_issued">

<class>com.javatpoint.mapping.Student</class>
<class>com.javatpoint.mapping.Library</class>

<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/mapping_db"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="eclipselink.logging.level" value="SEVERE"/>
<property name="eclipselink.ddl-generation" value="create-or-extend-
tables"/>
</properties>

</persistence-unit>
</persistence>

d) OneToOneExample.java

import javax.persistence.*;
import com.javatpoint.mapping.*;

public class OneToOneExample {


public static void main(String[] args) {

EntityManagerFactory emf =
Persistence.createEntityManagerFactory( "Book_issued" );
EntityManager em = emf.createEntityManager( );
em.getTransaction( ).begin( );

Student st1=new Student();


st1.setS_id(1);
st1.setS_name("Vipul");

Student st2=new Student();


st2.setS_id(2);
st2.setS_name("Vimal");

em.persist(st1);
em.persist(st2);

Library lib1=new Library();


lib1.setB_id(101);
lib1.setB_name("Data Structure");
lib1.setStud(st1);

Library lib2=new Library();


lib2.setB_id(102);
lib2.setB_name("DBMS");
lib2.setStud(st2);

em.persist(lib1);
em.persist(lib2);

em.getTransaction().commit();

em.close();
emf.close();
}

16) One-To-Many Mapping


------------------------
In this type of association the instance of one entity can be mapped with any
number of instances of another entity.
In this example, we will create a One-To-Many relationship between a Student and
Library in such a way that one student can be issued more than one type of book.

@OneToMany

a) Student.java

@OneToMany(targetEntity=Library.class)
private List books_issued;

17) Many-To-One Mapping


------------------------
A collection of entities can be associated with the similar entity.
In this example, we will create a Many-To-One relationship between a Student and
Library in such a way that more than one student can issued the same book.
@ManyToOne

@ManyToOne
private Library lib;

18) Many-To-Many Mapping


-------------------------
Any number of entities can be associated with a collection of other entities.
@ManyToMany
In this example, we will create a Many-To-Many relationship between a Student and
Library in such a way that any number of students can be issued any type of books.

a) Student.java
@ManyToMany(targetEntity=Library.class)
private List lib;

2) Library.java
@ManyToMany(targetEntity=Student.class)
private List stud;

19) JPA Cascading Operations


------------------------------
In JPA, if any operation is applied on an entity then it will perform on that
particular entity only. These operations will not be applicable to the other
entities
that are related to it.

To establish a dependency between related entities, JPA provides


javax.persistence.CascadeType enumerated types that define the cascade operations.
These cascading operations can be defined with any type of mapping i.e. One-to-One,
One-to-Many, Many-to-One, Many-to-Many.

Following are the enums used to perform cascading operations.

Cascade Operations Description


PERSIST In this cascade operation, if the parent entity is
persisted then all its related entity will also be persisted.
MERGE In this cascade operation, if the parent entity is merged
then all its related entity will also be merged.
DETACH In this cascade operation, if the parent entity is
detached then all its related entity will also be detached.
REFRESH In this cascade operation, if the parent entity is
refreshed then all its related entity will also be refreshed.
REMOVE In this cascade operation, if the parent entity is
removed then all its related entity will also be removed.
ALL In this case, all the above cascade operations can be applied
to the entities related to parent entity.

20) JPA Cascade Persist


--------------------------
The cascade persist is used to specify that if an entity is persisted then all its
associated child entities will also be persisted.
The following syntax is used to perform cascade persist operation.
@OneToOne(cascade=CascadeType.PERSIST)
@OneToOne(cascade=CascadeType.PERSIST)
private Subject sub;

21) JPA Cascade Remove


------------------------
The cascade remove is used to specify that if the parent entity is removed then all
its related entities will also be removed.
The following syntax is used to perform cascade remove operation: -

@OneToOne(cascade=CascadeType.REMOVE)

@OneToOne(cascade={CascadeType.REMOVE})
private Subject sub;

22) JPA JPQL Introduction


-------------------------
The JPQL (Java Persistence Query Language) is an object-oriented query language
which is used to perform database operations on persistent entities.
Instead of database table, JPQL uses entity object model to operate the SQL
queries. Here, the role of JPA is to transform JPQL into SQL.
Thus, it provides an easy platform for developers to handle SQL tasks.

It can perform join operations.


It can update and delete data in a bulk.
It can perform aggregate function with sorting and grouping clauses.
Single and multiple value result types.

23) JPQL Features


-------------------
It is a platform-independent query language.
It is simple and robust.
It can be used with any type of database such as MySQL, Oracle.
JPQL queries can be declared statically into metadata or can also be dynamically
built in code.

24) Creating Queries in JPQL


-----------------------------

Query query = em.createQuery("Select s.s_name from StudentEntity s");


This method creates dynamic queries that can be defined within business logic.

@NamedQuery(name = "find name" , query = "Select s from StudentEntity s")


This method is used to create static queries that can be defined in entity class.

Query query = em.createNamedQuery("find name");

Now, we can control the execution of query by the following Query interface
methods: -

int executeUpdate() - This method executes the update and delete operation.
int getFirstResult() - This method returns the first positioned result the query
object was set to retrieve.
int getMaxResults() - This method returns the maximum number of results the query
object was set to retrieve.
java.util.List getResultList() - This method returns the list of results as an
untyped list.
Query setFirstResult(int startPosition) - This method assigns the position of first
result to retrieve.
Query setMaxResults(int maxResult) - This method assigns the maximum numbers of
result to retrieve.

25) JPA Criteria API


--------------------
The Criteria API is one of the most common ways of constructing queries for
entities and their persistent state.
It is just an alternative method for defining JPA queries.

Criteria API defines a platform-independent criteria queries, written in Java


programming language.
It was introduced in JPA 2.0. The main purpose behind this is to provide a type-
safe way to express a query.

Leave this for now. If they asked in interview then come and explore.

26) JPA Inheritence Overview


-----------------------------

Inheritence is a key feature of object-oriented programming language in which a


child class can acquire the properties of its parent class.
This feature enhances reusability of the code.

The relational database doesn't support the mechanism of inheritance. So, Java
Persistence API (JPA) is used to map the key features of inheritance in
relational database model.

27) JPA Inheritance Annotations


-------------------------------
@Inheritence - This annotation is applied on the root entity class to define the
inheritance strategy.
If no strategy type is defined with this annotation then it follows
single table strategy.
@MappedSuperclass - This annotation is applied to the classes that are inherited by
their subclasses.
The mapped superclass doesn't contain any separate table.
@DiscriminatorColumn - The discriminator attribute differentiates one entity from
another. Thus, this annotation is used to provide the name of discriminator column.

It is required to specify this annotation on the root


entity class only.
@DiscriminatorValue - This annotation is used to specify the type of value that
represents the particular entity.
It is required to specify this annotation on the sub-entity
classes.

Leave this for now. If they asked in interview then come and explore.

You might also like