JPA Interview Questions and Answers for Beginners and Experienced


In this article, we will discuss important Java Persistence API interview questions and answers.

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.

Read more about JPA at JPA Tutorial - Java Persistence API

2. What is Object-Relational Mapping?

The term Object/Relational Mapping refers to the technique of mapping data from an object model representation to a relational data model representation (and vice versa).
For example, let's look at below diagram shows mapping between Student java model and database relational student table.
Read more about Hibernate ORM Framework at Hibernate ORM Framework Tutorial

3. What are the advantages of JPA?

The advantages of JPA are given below.
  • The burden of interacting with the database reduces significantly by using JPA.
  • The user programming becomes easy by concealing the O/R mapping and database access processing.
  • The cost of creating the definition file is reduced by using annotations.
  • We can merge the applications used with other JPA providers
  • Using different implementations can add the features to the standard Implementation which can later be the part of JPA specification.

4. What is the Difference Between JPA and Hibernate?

As we know that JPA is just a specification, meaning there is no implementation. You can annotate your classes as much as you would like with JPA annotations, however, without an implementation, nothing will happen. Think of JPA as the guidelines that must be followed or an interface, while Hibernate's JPA implementation is code that meets the API as defined by the JPA specification and provides the under the hood functionality.

In short, JPA is the interface while Hibernate is the implementation.

Traditionally there have been multiple Java ORM solutions:
Each of the above implementation defining its own mapping definition or client API. The JPA expert group gathered the best of all these tools and so they created the Java Persistence API standard.

The benefit of this is that you can swap out Hibernate's implementation of JPA for another implementation of the JPA specification.

5. Defining a JPA Entity Class

A JPA entity class is a POJO (Plain Old Java Object) class, i.e. an ordinary Java class that is marked (annotated) as having the ability to represent objects in the database. Conceptually this is similar to serializable classes, which are marked as having the ability to be serialized.
Read more about JPA entity at JPA Entity Class Basics.

The Point Entity Class Example

The following Point class, which represents points in the plane, is marked as an entity class, and accordingly, provides the ability to store Point objects in the database and retrieve Point objects from the database:
@Entity
public class Point {
    // Persistent Fields:
    private int x;
    private int y;

    // Constructor:
    Point (int x, int y) {
        this.x = x;
        this.y = y;
    }

    // Accessor Methods:
    public int getX() { return this.x; }
    public int getY() { return this.y; }

    // String Representation:
    @Override
    public String toString() {
        return String.format("(%d, %d)", this.x, this.y);
    }
}
As you can see above, an entity class is an ordinary Java class. The only unique JPA addition is the @Entityannotation, which marks the class as an entity class.

6. What are Requirements or Rules to Create JPA Entity Classes?

Let's discuss what are the rules or requirements to create a JPA entity class. An entity class must follow these requirements.
  • The class must be annotated with the javax.persistence.Entity annotation.
  • The class must have a public or protectedno-argument constructor. The class may have other constructors.
  • The class must not be declared final. No methods or persistent instance variables must be declared final.
  • If an entity instance is passed by value as a detached object, such as through a session bean's remote business interface, the class must implement the Serializable interface.
  • Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes.
  • Persistent instance variables must be declared private, protected, or package-private and can be accessed directly only by the entity class's methods. Clients must access the entity's state through accessor or business methods.

7. Java Persistence Query language

JPQL is Java Persistence Query Language defined in JPA specification. It is used to create queries against entities to store in a relational database. JPQL is developed based on SQL syntax. But it won’t affect the database directly.

JPQL can retrieve information or data using SELECT clause, can do bulk updates using UPDATE clause and DELETE clause. EntityManager.createQuery() API will support for querying language.

8. Explain JPA Architecture or Explain the core classes and interfaces of JPA API?

Class Level Architecture

The following image shows the class level architecture of JPA. It shows the core classes and interfaces of JPA.

Let's describe each of the units shown in the above architecture.
  1. EntityManagerFactory - This is a factory class of EntityManager. It creates and manages multiple EntityManager instances.
  2. EntityManager - It is an Interface, it manages the persistence operations on objects. It works like a factory for Query instance.
  3. Entity - Entities are the persistence objects, stores as records in the database.
  4. EntityTransaction - It has one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class.
  5. Persistence - This class contains static methods to obtain EntityManagerFactory instance.
  6. Query - This interface is implemented by each JPA vendor to obtain relational objects that meet the criteria.
Read more about JPA architecture in-depth at JPA Architecture

9. What is an Entitymanager?

An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed.
The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities.
In short, a connection to a database is represented by an EntityManager instance, which also provides functionality for performing operations on a database. Many applications require multiple database connections during their lifetime. For instance, in a web application, it is common to establish a separate database connection, using a separate EntityManager instance, for every HTTP request.
Read more about EntityManager in-depth at JPA EntityManager Interface with Example

10. Name required Steps to Persist JPA entity in a database?

Step1: First create an instance of EntityManagerFactory class using Persistence class.
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("PERSISTENCE");
  • 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 the persistence unit passed in the Persistence.xml file.
Step 2:  Obtaining an EntityManager
Once we have an EntityManagerFactory we can easily obtain an EntityManager instance:
EntityManager entityManager = entityManagerFactory.createEntityManager();
  • EntityManager - An EntityManager is an interface
  • createEntityManager() method - It creates new application-managed EntityManager
Step 3: Using an EntityTransaction
Operations that modify database content, such as a store, update, and delete should only be performed within an active transaction.
Given an EntityManager, entityManager, it is very easy to begin a transaction:
entityManager.getTransaction().begin();
  • getTransaction() method - This method returns the resource-level EntityTransaction object.
  • begin() method - This method is used to start the transaction.
Step 4: Closing EntityManagerFactory and EntityManager Resources
The EntityManagerFactory is also used to close the database once we are finished using it:
entityManagerFactory.close();
When the connection to the database is no longer needed the EntityManager can be closed:
entityManager.close();

11. What are the steps to insert an entity?

12. What are the steps to find an entity?

13. What are the steps to update an entity?

14. What are the steps to delete an entity?

15. What Data Types Are Allowed in the Attributes of the Entity Class (Fields or Properties)?

The persistent state of an entity can be accessed through either the entity's instance variables or properties. The fields or properties must be of the following Java language types:
  1. java.lang.String
  2. Other serializable types, including:
  • Wrappers of Java primitive types
  • java.math.BigInteger
  • java.math.BigDecimal
  • java.util.Date
  • java.util.Calendar
  • java.sql.Date
  • java.sql.Time
  • java.sql.TimeStamp
  • User-defined serializable types
  • byte[]
  • Byte[]
  • char[]
  • Character[]
  1. Other entities and/or collections of entities

16. What Is the Embeddable Class in JPA?


An embeddable class is a class that is not used by itself, only as part of one or more Entity classes. An entity class can contain both single embedded classes and collections of such classes. Also, such classes can be used as keys or map values. At runtime, each embedded class belongs to only one object of the Entity class and cannot be used to transfer data between the objects of the Entity classes (that is, such a class is not a common data structure for different objects). In general, such a class serves to make the definition of common attributes for several Entity, we can assume that JPA simply embeds into the Entity instead of an object of this class, the attributes it contains.

Check out a complete example at JPA- Using @Embeddable and @Embedded Annotation

17. What are the different types of entity mapping?

Following are the types of object-relational mapping: -
  • 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.
  • 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.
  • Many-to-one mapping: The Many-To-One mapping represents a single-valued association where a collection of entities can be associated with a similar entity. In the relational database, more than one row of an entity can refer to the same row of another entity.
  • 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.

18. What are the JPA Cascade Types?

JPA allows you to propagate the state transition from a parent entity to a child. For this purpose, the JPA javax.persistence.CascadeType defines various cascade types:
  • ALL - cascades all entity state transitions
  • PERSIST - cascades the entity persist operation.
  • MERGE - cascades the entity merge operation.
  • REMOVE - cascades the entity remove operation.
  • REFRESH - cascades the entity refresh operation.
  • DETACH - cascades the entity detach operation.
Entities that use relationships often have dependencies on the existence of the other entity in the relationship. For example, a line item is part of an order; if the order is deleted, the line item also should be deleted. This is called a cascade delete relationship.

Read more about JPA cascade types with a complete example at Guide to JPA and Hibernate Cascade Types

19. What are the features of JPQL?

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

20. What are the JPA Primary Key Generation Strategies?

The JPA specification supports 4 different primary key generation strategies which generate the primary key values programmatically or use database features, like auto-incremented columns or sequences.

1. GenerationType.AUTO
2. GenerationType.IDENTITY
3. GenerationType.SEQUENCE
4.GenerationType.TABLE

Know more about these primary key generation strategies with examples at Hibernate/JPA - Primary Key Generation Strategies

21. Explain JPA Inheritance Strategies?

 JPA specification provides several strategies:
  1. MappedSuperclass - Inheritance is implemented in the domain model only without reflecting it in the database schema. See MappedSuperclass.
  2. Single table - The domain model class hierarchy is materialized into a single table which contains entities belonging to different class types. See Single table.
  3. Joined table - The base class and all the subclasses have their own database tables and fetching a subclass entity requires a join with the parent table as well. See Joined table.
  4. Table per class - Each subclass has its own table containing both the subclass and the base class properties.
Read more at Hibernate/JPA - Inheritance Mapping.
Learn everything about JPA at JPA Tutorial - Java Persistence API
Leave a comment if you have other interview questions regarding Java Persistence API  so that I will add this list which will help others to prepare for their interview.

Comments