Spring Data JPA

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

1. What is the Java Persistence API?

The Java Persistence API (JPA) is the specification of Java that 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. As JPA is just a
specification, it doesn't perform any operation by itself. It requires an
implementation. Therefore, ORM tools like Hibernate, TopLink, and iBatis implements
JPA specifications for data persistence. The first version of the Java Persistence API,
JPA 1.0 was released in 2006 as a part of EJB 3.0 specification.

2. What is the object-relational mapping?


The object-relational mapping is a mechanism which is used to develop and maintain
a relationship between an object and the relational database by mapping an object
state into the database column. It converts attributes of programming code into
columns of the table. It is capable of handling various database operations easily
such as insertion, updation, deletion, etc

3. What are the embeddable classes?


Embeddable classes represent the state of an entity but do not have a persistent
identity of their own. The objects of such classes share the identity of the entity
classes that owns it. An Entity may have single-valued or multivalued embeddable
class attributes.

4. List some ORM frameworks.


Following are the various frameworks that function on ORM mechanism: -

o Hibernate
o TopLink
o ORMLite
o iBATIS
o JPOX

5. What are the steps to persist an entity object?


The following steps are performed to persist an entity object.
o Create an entity manager factory object. The EntityManagerFactory interface
present in java.persistence package is used to provide an entity manager.

EntityManagerFactory emf=Persistence.createEntityManagerFactory("St
udent_details");  

o Obtain an entity manager from the factory.

EntityManager em=emf.createEntityManager();  

o Initialize an entity manager.

em.getTransaction().begin();  

o Persist the data into the relational database.

em.persist(s1);  

o Closing the transaction

em.getTransaction().commit();  

o Release the factory resources.

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

6. What is the JPQL?


JPQL is the Java Persistence query language defined in JPA specification. It is used to
construct the queries.

7. What are the steps to insert an entity?


We can easily insert the data into the database through the entity. The EntityManager
provides persist() method to add records. The following steps are used to insert the record
into the database.

Create an entity class, for example, Student.java with the attribute student_name.

package com.javatpoint.jpa.student;  
import javax.persistence.*;  
  
@Entity  
@Table(name="student")  
public class Student {  
  
    @Id  
    private String s_name;  
      
    public StudentEntity(String s_name) {  
        super();  
        this.s_name = s_name;  
    }  
  
    public StudentEntity() {  
        super();  
    }  
  
    public String getS_name() {  
        return s_name;  
    }  
  
    public void setS_name(String s_name) {  
        this.s_name = s_name;  
    }  
}  

o Now, map the entity class and other databases configuration


in Persistence.xml file.

<persistence>  
<persistence-unit name="Student_details">  
      
    <class>com.javatpoint.jpa.student.StudentEntity</class>  
  
<properties>  
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Dri
ver"/>  
<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>  
o Create a persistence class named as PersistStudent.java under
com.javatpoint.jpa.persist package to persist the entity object with data

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_name("Gaurav");  
        em.persist(s1);  
        em.getTransaction().commit();  
        emf.close();  
        em.close();  
    }  
}  

8. What are the steps to find an entity?


To find an entity, EntityManager interface provides find() method that searches an
element by the primary key. The following steps are used to find an entity in the
record.

Create an entity class named as StudentEntity.java under


com.javatpoint.jpa.student package that contains attributes s_name.

1. package com.javatpoint.jpa.student;  
2. import javax.persistence.*;  
3.   
4. @Entity  
5. @Table(name="student")  
6. public class StudentEntity {  
7.   
8.     @Id  
9.     private String s_name;  
10.     private int s_id;  
11.     public StudentEntity(String s_name, int s_id) {  
12.         super();  
13.         this.s_name = s_name;  
14.         this.s_id = s_id;  
15.     }  
16.   
17.     public StudentEntity() {  
18.         super();  
19.     }  
20.   
21.       
22.     public String getS_id() {  
23.         return s_id;  
24.     }  
25.   
26.     public void setS_id(int s_id) {  
27.         this.s_name = s_id;  
28.     }  
29.     public String getS_name() {  
30.         return s_name;  
31.     }  
32.   
33.     public void setS_name(String s_name) {  
34.         this.s_name = s_name;  
35.     }  
36. }  

o Now, map the entity class and other databases configuration


in Persistence.xml file.

<persistence>  
<persistence-unit name="Student_details">  
      
    <class>com.javatpoint.jpa.student.StudentEntity</class>  
  
<properties>  
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Dri
ver"/>  
<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>  

o Create a persistence class named as FindStudent.java under


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

package com.javatpoint.jpa.find;  
import javax.persistence.*;  
  
import com.javatpoint.jpa.student.*;  
  
public class FindStudent {  
    public static void main(String args[])  
    {  
        EntityManagerFactory emf=Persistence.createEntityManagerFactory("
Student_details");  
        EntityManager em=emf.createEntityManager();  
          
      
          
        StudentEntity s=em.find(StudentEntity.class,101);  
          
        System.out.println("Student id = "+s.getS_id());  
        System.out.println("Student Name = "+s.getS_name());  
        System.out.println("Student Age = "+s.getS_age());  
          
    }  
}  

9) What are the steps to update an entity?


JPA allows us to change the records in the database by updating an entity. The
following steps are to be performed to update the entity

o Create an entity class named as StudentEntity.java under


com.javatpoint.jpa.student package, that contains attribute s_id and s_name.

StudentEntity.java
package com.javatpoint.jpa.student;  
import javax.persistence.*;  
  
@Entity  
@Table(name="student")  
public class StudentEntity {  
  
    @Id  
    private String s_name;  
    private int s_id;  
    public StudentEntity(String s_name, int s_id) {  
        super();  
        this.s_name = s_name;  
        this.s_id = s_id;  
    }  
  
    public StudentEntity() {  
        super();  
    }  
  
      
    public String getS_id() {  
        return s_id;  
    }  
  
    public void setS_id(int s_id) {  
        this.s_name = s_id;  
    }  
    public String getS_name() {  
        return s_name;  
    }  
  
    public void setS_name(String s_name) {  
        this.s_name = s_name;  
    }  
}  

Now, map the entity class and other databases configuration in Persistence.xml
file.

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 UpdateStudent.java under


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

UpdateStudent.java

package com.javatpoint.jpa.update;  
import javax.persistence.*;  
  
import com.javatpoint.jpa.student.*;  
public class UpdateStudent {  
      
    public static void main(String args[])  
    {  
        EntityManagerFactory emf=Persistence.createEntityManagerFactory("Studen
t_details");  
        EntityManager em=emf.createEntityManager();  
        StudentEntity s=em.find(StudentEntity.class,102);  
        System.out.println("Before Updation");  
        System.out.println("Student Name = "+s.getS_name());  
        s.setName("Ayush");  
        System.out.println("After Updation");  
        System.out.println("Student Name = "+s.getS_name());  
    }  
}  

10. What are the steps to delete an entity?


To delete a record from the database, EntityManager interface provides remove()
method. The remove() method uses the primary key to delete the particular record.
The following examples are to be performed to delete an entity.
o Create an entity class named as StudentEntity.java under
com.javatpoint.jpa.student package that contains attribute s_id and s_name.

package com.javatpoint.jpa.student;  
import javax.persistence.*;  
  
@Entity  
@Table(name="student")  
public class StudentEntity {  
  
    @Id  
    private int s_id;  
    private String s_name;  
      
    public StudentEntity(int s_id, String s_name) {  
        super();  
        this.s_id = s_id;  
        this.s_name = s_name;  
    }  
  
    public StudentEntity() {  
        super();  
    }  
  
    public int getS_id() {  
        return s_id;  
    }  
  
    public void setS_id(int s_id) {  
        this.s_id = s_id;  
    }  
  
    public String getS_name() {  
        return s_name;  
    }  
  
    public void setS_name(String s_name) {  
        this.s_name = s_name;  
    }     
}  

Now, map the entity class and other databases configuration in Persistence.xml
file.
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.Dri
ver"/>  
<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>  

Deletion.java

package com.javatpoint.jpa.delete;  
import javax.persistence.*;  
import com.javatpoint.jpa.student.*;  
  
public class DeleteStudent {  
  
    public static void main(String args[])  
    {  
    EntityManagerFactory emf=Persistence.createEntityManagerFactory("Stu
dent_details");  
    EntityManager em=emf.createEntityManager();  
em.getTransaction().begin();  
  
    StudentEntity s=em.find(StudentEntity.class,102);  
em.remove(s);  
em.getTransaction().commit();  
emf.close();  
em.close();  
  
    }  
}  

11. What are the different types of entity mapping?


Following are the types of object-relational mapping: -

o One-to-one mapping: The one-to-one mapping represents a single-valued


association where an instance of one entity is associated with an instance of
another entity. In this type of association, one instance of source entity can be
mapped with at most one instance of the target entity.
o One-To-Many mapping: The One-To-Many mapping comes into the
category of collection-valued association where an entity is associated with a
collection of other entities. In this type of association, the instance of one
entity can be mapped with any number of instances of another entity.
o Many-to-one mapping The Many-To-One mapping represents a single-
valued association where a collection of entities can be associated with the
similar entity. In the relational database, more than one row of an entity can
refer to the same row of another entity.
o Many-to-many mapping The Many-To-Many mapping represents a
collection-valued association where any number of entities can be associated
with a collection of other entities. In the relational database, more than one
row of one entity can refer to more than one row of another entity.

12. Explain persistence life cycle of an object?


In persistence life cycle, the object lies in the following states:

o Transient - The object is called to be in the transient state when it is just


declared by using the new keyword. When an object remains in the transient
state, it doesn't contain any identifier(primary key) in the database.
o Persistence - In this state, an object is associated with the session and either
saved to a database or retrieved from the database. When an object remains
in the persistence state, It contains a row of the database and consists of an
identifier value. We can make an object persistent by associating it with the
hibernate session.
o Detached - The object enters into a detached state when the hibernate
session is closed. The changes made to the detached objects are not saved to
the database.

13. What are the different types of identifier generation?


Following are the types of id generation strategy required to specify with
@GeneratedValue annotation: -

o Automatic Id generation - In this case, the application doesn't care about the
kind of id generation and hand over this task to the provider. If any value is
not specified explicitly, the generation type defaults to auto.
o Id generation using a table - The identifiers can also be generated using a
database table.
o Id generation using a database sequence - Databases support an internal
mechanism for id generation called sequences. To customize the database
sequence name, we can use the JPA @SequenceGenerator annotation.
o Id generation using a database identity - In this approach, whenever a row is
inserted into the table, a unique identifier is assigned to the identity column
that can be used to generate the identifiers for the objects.

14. What are the constraints on an entity class?


An entity class must fulfill the following requirements:

o The class must have a no-argument constructor.


o The class can't be final.
o The class must be annotated with @Entity annotation.
o The class must implement a Serializable interface if value passes an empty
instance as a detached object.

15. What is the Criteria API?


The Criteria API is a specification that provides type-safe and portable criteria queries
written using Java programming language APIs. It 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.

You might also like