JPA
JPA
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.
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
}
EntityManager em=emf.createEntityManager();
EntityManager - An EntityManager is an interface
createEntityManager() method - It creates new application-managed EntityManager
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.
em.getTransaction().commit();
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() {
super();
}
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>
c) PersistStudent.java
package com.javatpoint.jpa.persist;
import com.javatpoint.jpa.student.*;
import javax.persistence.*;
public class PersistStudent {
EntityManagerFactory
emf=Persistence.createEntityManagerFactory("Student_details");
EntityManager em=emf.createEntityManager();
em.getTransaction().begin();
em.persist(s1);
em.persist(s2);
em.persist(s3);
em.getTransaction().commit();
emf.close();
em.close();
}
}
a) Employee.java
package com.javatpoint.jpa;
import java.util.*;
import javax.persistence.*;
@Entity
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int e_id;
private String e_name;
b) Address.java
package com.javatpoint.jpa;
import javax.persistence.*;
@Embeddable
public class Address {
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{
EntityManagerFactory
emf=Persistence.createEntityManagerFactory("Collection_Type");
EntityManager em=emf.createEntityManager();
em.getTransaction().begin();
em.persist(e1);
em.persist(e2);
em.getTransaction().commit();
em.close();
emf.close();
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() {
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.*;
EntityManagerFactory emf =
Persistence.createEntityManagerFactory( "Book_issued" );
EntityManager em = emf.createEntityManager( );
em.getTransaction( ).begin( );
em.persist(st1);
em.persist(st2);
em.persist(lib1);
em.persist(lib2);
em.getTransaction().commit();
em.close();
emf.close();
}
@OneToMany
a) Student.java
@OneToMany(targetEntity=Library.class)
private List books_issued;
@ManyToOne
private Library lib;
a) Student.java
@ManyToMany(targetEntity=Library.class)
private List lib;
2) Library.java
@ManyToMany(targetEntity=Student.class)
private List stud;
@OneToOne(cascade=CascadeType.REMOVE)
@OneToOne(cascade={CascadeType.REMOVE})
private Subject sub;
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.
Leave this for now. If they asked in interview then come and explore.
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.
Leave this for now. If they asked in interview then come and explore.