Practice
Resources
Contests
Online IDE
New
Free Mock
Events New Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
logo
Events
Attend free live masterclass hosted by top tech professionals
New
Scaler
Explore Offerings by SCALER
exit-intent-icon

Download Interview guide PDF

Before you leave, take this JPA Interview Questions interview guide with you.
Get a Free Personalized Career Roadmap
Answer 4 simple questions about you and get a path to a lucrative career
expand-icon Expand in New Tab
/ Interview Guides / JPA Interview Questions

JPA Interview Questions

Last Updated: Jan 02, 2024

Download PDF


Your requested download is ready!
Click here to download.
Certificate included
About the Speaker
What will you Learn?
Register Now

Introduction

If you are a fresh graduate looking for a job in the software development industry, or an experienced developer planning to switch to a new job, it is essential to prepare for the interviews. One of the essential skills for any Java developer is understanding Java Persistence API (JPA), which is the standard specification for mapping Java objects to relational databases.

In this article, we have compiled a list of JPA Interview Questions that are essential and frequently asked during the interviews. We have categorized these questions into the following sections: 

The questions in the first section are designed to test the basic knowledge of JPA, while the questions in the second section are more advanced and require a deeper understanding of the framework.

So, let's get started and dive into the list of important questions for the JPA interview.

JPA Interview Questions for Freshers

1. What types of cascades does JPA support?

JPA supports several types of cascading operations to propagate changes made to entities across relationships. The cascading operations can be specified using the “javax.persistence.CascadeType” enumeration. Here are the different types of cascading operations supported by JPA:

  • CascadeType.ALL: This cascades all operations - including persist, merge, remove, and refresh - from the parent entity to the associated child entities.
  • CascadeType.PERSIST: This cascades the persistent operation from the parent entity to the associated child entities.
  • CascadeType.MERGE: This cascades the merge operation from the parent entity to the associated child entities.
  • CascadeType.REMOVE: This cascades the remove operation from the parent entity to the associated child entities.
  • CascadeType.REFRESH: This cascades the refresh operation from the parent entity to the associated child entities.
  • CascadeType.DETACH: This cascades the detach operation from the parent entity to the associated child entities.
  • CascadeType.DETACH: This cascades the lock operation from the parent entity to the associated child entities.
Create a free personalised study plan Create a FREE custom study plan
Get into your dream companies with expert guidance
Get into your dream companies with expert..
Real-Life Problems
Prep for Target Roles
Custom Plan Duration
Flexible Plans

2. What is the purpose of the EntityManagerFactory in Spring Data JPA?

EntityManagerFactory in Spring Data JPA serves the following purposes:

  • The EntityManagerFactory in Spring Data JPA is responsible for creating EntityManager instances. 
  • It reads the persistence configuration and creates EntityManager instances based on that configuration. 
  • The EntityManagerFactory manages the lifecycle of EntityManager instances and is thread-safe. 
  • It is responsible for managing the connection to the database and can be configured with various properties to control the behavior of the EntityManager instances it creates. 
  • In Spring Data JPA, the EntityManagerFactory is usually created automatically by the framework and injected into the application's code.

3. Difference between JpaRepository.save() and JpaRepository.saveAndFlush() methods?

  JpaRepository.save() JpaRepository.saveAndFlush()
Execution It saves an entity to the database and returns the saved entity. It saves an entity to the database and immediately flushes the changes to the database.
Return Value It returns the saved entity. It returns the saved entity.
Transaction The changes made to the entity are not immediately persisted in the database. They are persisted when the current transaction is committed. The changes made to the entity are immediately persisted to the database, regardless of whether the current transaction is committed or not.
Use Case Use this method when you want to save an entity and continue working with it in the same transaction. Use this method when you want to save an entity and immediately see the changes reflected in the database.
Performance This method is faster than saveAndFlush() because it does not immediately persist changes to the database. This method is slower than save() because it immediately persists changes to the database, which can be a performance bottleneck if used excessively.
You can download a PDF version of Jpa Interview Questions.

Download PDF


Your requested download is ready!
Click here to download.

4. What is the purpose of the @Transactional annotation in JPA?

The @Transactional annotation in JPA is used to indicate that a method should be executed within a transaction. It is used to define the scope of a transaction, which determines when changes made to the database will be committed. It can be applied at the class or method level, and it is typically used with the Spring Framework's declarative transaction management feature.

When a method annotated with @Transactional is called, a transaction will be started before the method is executed, and any changes made to the database within the method will be persisted to the database when the transaction is committed. If an exception is thrown within the method, the transaction will be rolled back, and any changes made to the database within the method will be discarded.

Example of using the @Transactional annotation in JPA:

@Service
@Transactional
public class EmployeeService {
    @Autowired
    private EntityManager entityManager;

    public void createEmployee(Employee employee) {
        entityManager.persist(employee);
    }

    public void updateEmployee(Employee employee) {
        entityManager.merge(employee);
    }

    public void deleteEmployee(Employee employee) {
        entityManager.remove(employee);
    }

    public Employee findEmployeeById(Long id) {
        return entityManager.find(Employee.class, id);
    }
}

In this example, the @Transactional annotation is applied to the EmployeeService class, which means that all public methods in the class will be executed within a transaction. When any of the CRUD methods are called, a transaction will be started before the method is executed, and any changes made to the database will be persisted when the transaction is committed.

5. What is the difference between a detached and attached entity in JPA?

  Attached Entity Detached Entity
Definition An entity that is currently being managed by the persistence context. An entity that was previously managed by the persistence context but is no longer attached.
Persistence Context The entity is associated with a persistence context. The entity is not associated with a persistence context.
Entity State The entity is in a synchronized state with the database. The entity is not in a synchronized state with the database.
Automatic Updates Any changes made to the entity's state are automatically synchronized with the database. Any changes made to the entity's state are not automatically synchronized with the database.
Persistence Operations The entity can be used to perform CRUD operations using EntityManager without any additional steps. The entity needs to be reattached to a persistence context before any CRUD operations can be performed.
Identity The entity has a unique identity within the persistence context. The entity may not have a unique identity within the persistence context if there are multiple detached copies of the same entity.
Performance May have a negative impact on performance due to the overhead of tracking changes to the entity's state. May have a positive impact on performance by reducing the amount of memory and processing power required to manage the entity.

Learn via our Video Courses

6. What is JPA?

Java Persistence API (JPA) is a specification for managing data persistence in Java applications. JPA is used to simplify the process of writing code for data persistence by providing a high-level abstraction layer over the underlying data storage technology, such as relational databases. JPA helps in mapping Java objects to relational database tables and allows developers to perform CRUD (create, read, update, delete) operations on data. JPA is often used in coexistence with Hibernate, a popular open-source ORM (object-relational mapping) framework. It is a part of the Java EE platform and is commonly used in enterprise applications.

7. What is the purpose of the @JoinColumn annotation in JPA?

The @JoinColumn annotation in JPA is used to specify a join column for a relationship mapping between two entities. It is used to define the columns in a table that will be used to establish the association between two entities, where one entity is the owner of the relationship (the one that has the foreign key column), and the other is the inverse side.

The @JoinColumn annotation can be applied to a field or property that is mapped as a foreign key column in the database. It allows you to specify the name of the column, its type, its nullable attribute, and its foreign key constraints. You can also use the @JoinColumn annotation to specify the name of the table that contains the foreign key column.

The @JoinColumn annotation can be used with the @ManyToOne, @OneToOne, @OneToMany, and @ManyToMany annotations to define the join columns for the relationship mapping.

Here's an example of using the @JoinColumn annotation to define a join column in JPA:

@Entity
public class Employee {
    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    @JoinColumn(name="department_id")
    private Department department;
    
    // other fields and methods
}
Advance your career with   Mock Assessments Refine your coding skills with Mock Assessments
Real-world coding challenges for top company interviews
Real-world coding challenges for top companies
Real-Life Problems
Detailed reports

8. What is the difference between EntityManager.find() and EntityManager.getReference() methods in JPA?

EntityManager.find() EntityManager.getReference()
It returns the entity instance immediately if it exists in the persistence context or the database. It returns a "reference" to the entity, which may not actually be loaded from the database until it is accessed.
If the entity instance is not found in the persistence context or the database, it returns null. If the entity instance is not found in the persistence context or the database, an EntityNotFoundException will be thrown when any method other than getId() is called on the reference.
It immediately loads the entity from the database and returns it as a fully initialized object. It returns a lightweight reference object that only contains the entity's primary key and does not actually load the entity from the database until a method other than getId() is called on the reference.
It can be used to retrieve an entity in either a managed or detached state. It only returns a managed entity if it already exists in the persistence context, otherwise returns a "hollow" reference that is not managed by the persistence context.
It throws an IllegalArgumentException if the argument passed to the method is not a valid entity type. It throws an EntityNotFoundException if the entity does not exist in the database.

9. What is the purpose of EntityManager in JPA?

The EntityManager in JPA is the primary interface through which an application interacts with the Persistence Context, which is responsible for managing the lifecycle of entity objects and their persistence in the database. The EntityManager provides a set of APIs for performing CRUD (Create, Read, Update, Delete) operations on the database using the entity objects.

The EntityManager is responsible for the following tasks:

  • Creating and removing entity objects.
  • Retrieving entity objects from the database.
  • Updating and persisting changes made to entity objects.
  • Managing the association between entities.
  • Managing the lifecycle of entity objects.
  • Executing queries on the database using JPQL (Java Persistence Query Language).
  • Caching entity objects for improved performance

The EntityManager API provides several methods for performing these tasks, such as ’persist()’, ‘find()’, ‘merge()’, ‘remove()’, and ‘createQuery()’. The EntityManager is typically obtained from a PersistenceContext, which is created and managed by the JPA provider, either by injection or programmatically.

10. Describe in detail about the Persistence Unit in JPA?

A Persistence Unit in JPA is a set of one or more entity classes that are managed together as a unit for the purpose of data persistence. It is a logical grouping of entity classes and their associated metadata, including their mappings to database tables, relationships between entities, and any other configuration information required to persist and retrieve data. A Persistence Unit is defined in a persistence.xml file, which is typically located in the META-INF directory of a Java project. This file contains metadata that describes the properties and configuration of the Persistence Unit, including the database connection details, the list of entity classes to be managed, and any additional configuration options.

When an application is deployed, the JPA provider reads the persistence.xml file and creates a Persistence Unit that is used to manage the entities within it. The application can then use the entity classes and the ‘EntityManager’ API to perform CRUD (Create, Read, Update, Delete) operations on the database.

JPA supports two types of Persistence Units:

  • Container-Managed Persistence Unit: In this type, the application server manages the lifecycle of the Persistence Unit and its associated EntityManager instances.
  • Application-Managed Persistence Unit: In this type, the application manages the lifecycle of the Persistence Unit and its associated EntityManager instances.

11. What are the various query methods in JPA to retrieve data from the database? List some of the most used methods.

In JPA, there are several query methods that can be used to retrieve data from the database:

  • createQuery(): This method creates a JPQL (Java Persistence Query Language) query that can be used to retrieve data from the database. JPQL queries are similar to SQL queries, but they operate on JPA entities rather than database tables.
  • createNamedQuery(): This method creates a named JPQL query that has been defined in the entity class using the @NamedQuery annotation.
  • createNativeQuery(): This method creates a native SQL query that can be used to retrieve data from the database using SQL syntax. Native SQL queries can be used when JPQL is not sufficient for complex queries or for accessing database-specific features.
  • find(): This method retrieves an entity from the database by its primary key.
  • getReference(): This method retrieves a reference to an entity from the database by its primary key, without actually loading the entity data from the database.
  • createQuery(criteriaQuery): This method creates a JPA Criteria API query that can be used to retrieve data from the database. The Criteria API provides a type-safe, object-oriented way to construct queries at runtime.
  • getSingleResult(): This method executes a query and returns a single result. If the query returns more than one result or no results, an exception is thrown.
  • getResultList(): This method executes a query and returns a list of results. If the query returns no results, an empty list is returned.

12. What is a Named Query in JPA? How is it used? And what are the benefits of using this?

In JPA, a named query is a pre-defined query that is given a name and can be used in multiple places in an application. It is defined in the entity class using the @NamedQuery annotation and can be used to retrieve entities based on specific criteria.

Consider the below snippet to understand better about this - 

@Entity
@NamedQuery(
    name = "Product.findByPriceGreaterThan",
    query = "SELECT p FROM Product p WHERE p.price > :price"
)
public class Product {
    // ...
}

In this example, we can see a named query called "Product.findByPriceGreaterThan", which selects all products whose price is greater than a given value. The query is defined using JPQL syntax and uses a named parameter ":price" to specify the price value.

To use the named query in our code, we can retrieve it using EntityManager's createNamedQuery() method and pass in the name of the query:

TypedQuery<Product> query = entityManager.createNamedQuery("Product.findByPriceGreaterThan", Product.class);
query.setParameter("price", 10.0);
List<Product> products = query.getResultList();

In this code snippet, we create a TypedQuery object using the named query "Product.findByPriceGreaterThan" and pass in the Product class as the expected result type. We then set the value of the named parameter ":price" to 10.0 and execute the query using getResultList() to retrieve a list of products that match the criteria.

Using named queries in JPA has several benefits, including:

  • Reusability: named queries can be defined once and used multiple times throughout the application.
  • Performance: named queries are compiled and cached by the JPA provider, which can improve performance for frequently used queries.
  • Maintenance: named queries can be easily modified or updated in a central location, rather than scattered throughout the codebase.

13. Difference between JPA Repository and CRUD Repository? Explain with the help of an example.

JPA Repository is an interface provided by Spring Data JPA that extends the JpaRepository interface. It provides a set of methods for performing common operations on entities, such as save, delete, findAll, and findById. In addition to these methods, it also allows you to define custom query methods using the @Query annotation.

On the other hand, CRUD Repository is an interface provided by Spring Data that provides a set of methods for performing CRUD (Create, Read, Update, Delete) operations on entities. It provides basic functionality for working with data, such as save, delete, findById, and findAll.

In short, JPA Repository extends the functionality of the CRUD Repository by providing additional methods and the ability to define custom queries. However, if you only need basic CRUD functionality, then using CRUD Repository may be sufficient. 

Example -

Let's say we have an entity called "Product" with the following properties: id, name, description, and price. We want to create a Spring Data repository to perform CRUD operations on this entity.

First, let's create a repository using the CRUD Repository interface:

import org.springframework.data.repository.CrudRepository;
public interface ProductRepository extends CrudRepository<Product, Long> {
}

This interface provides basic CRUD functionality for the Product entity, such as save(), delete(), findById(), and findAll().

Now let's create a repository using the JPA Repository interface:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findByPriceGreaterThan(double price);
    
    @Query("SELECT p FROM Product p WHERE p.name LIKE %?1%")
    List<Product> findByNameContaining(String keyword);
}

This interface extends the JpaRepository interface and provides additional methods, such as findByPriceGreaterThan() and findByNameContaining(). These methods are defined using Spring Data's method name query and the @Query annotation, respectively.

14. What are the advantages of using JPA over JDBC?

JPA is a higher-level abstraction of JDBC (Java Database Connectivity) that provides several advantages over JDBC. Here are some of the key advantages of using JPA over JDBC:

  • Object-Relational Mapping: It offers an Object-Relational Mapping (ORM) framework that enables developers to map Java objects to database tables without having to create SQL queries. Developers will have to write less code as a result, and the codebase will be simpler to maintain.
  • Portability: It is a standardized API that is independent of any specific database implementation. This means that applications written using JPA can be easily ported to different databases without having to rewrite the database access code.
  • Increased Productivity: It offers a higher-level API that is simpler and easier to use than JDBC. This reduces the amount of time that developers spend writing and debugging database access code, and allows them to focus on other aspects of the application.
  • Improved Performance: By minimizing the number of database queries that are run, it uses a caching mechanism that can enhance performance. This may lead to quicker response times and improved scalability.
  • Transaction Management: It offers a transaction management system that simplifies the process of managing database transactions. 
  • Object-Oriented Features: It provides support for object-oriented features such as inheritance and polymorphism. This allows developers to work with Java objects instead of relational tables, which is easy to maintain.

15. What is a database transaction and how is it used in JPA?

A database transaction is a sequence of database operations that are executed as a single logical unit of work. A transaction is typically used to ensure data consistency and integrity, by ensuring that either all of the operations in the transaction are executed, or none of them is executed.

In JPA, transactions are used to manage the interactions between Java code and the underlying relational database. JPA provides a transaction management system that allows developers to define and control transactions in their applications.

JPA defines a ‘javax.persistence.EntityTransaction’  interface that represents a transaction between a Java application and the database. A typical usage pattern for a JPA transaction involves the following steps:

  • Obtain an instance of the ‘EntityManager’  interface.
  • Begin a transaction using the ‘EntityTransaction’ interface's ‘begin()’ method.
  • Perform one or more database operations using the ‘EntityManager’ interface's persistence methods, such as ‘persist()’, ‘merge()’, or ‘remove()’.
  • Commit the transaction using the ‘EntityTransaction’ interface's ` method.

If any errors occur during the transaction, roll back the transaction using the ‘EntityTransaction’ interface's ‘rollback()’ method.

16. What is JPQL and how is it used in JPA?

JPQL stands for Java Persistence Query Language. It is a platform-independent object-oriented query language that is used to retrieve data from a relational database using Java Persistence API. JPQL is similar to SQL (Structured Query Language) in terms of syntax, but instead of operating on tables and columns, it operates on JPA entities and their corresponding attributes.

JPQL is used in JPA to create dynamic queries that can be executed against a relational database. These queries are defined as strings and can be executed using the JPA EntityManager interface. JPQL allows developers to write complex queries that can retrieve data from multiple tables, perform aggregations, and filter results based on conditions.

JPQL queries can be run against various databases without modification because it is intended to be portable across various databases. Additionally, JPQL supports object-oriented features like polymorphism and inheritance, enabling developers to create queries that interact with object hierarchies as compared to just flat tables.

Let’s look at the sample code to understand it better.

String jpql = "SELECT e FROM Employee e WHERE e.department = :dept";

TypedQuery<Employee> query = entityManager.createQuery(jpql, Employee.class);
query.setParameter("dept", "IT");

List<Employee> results = query.getResultList();

In this example, the JPQL query selects all Employee’ objects that belong to the ‘IT’ department. The query is executed using the ‘createQuery’ method of the EntityManager’ interface, and the setParameter’ method is used to bind the value of the ‘dept’ parameter to the query

17. What are entities in JPA? Explain the concept in detail.

In JPA, an entity is a lightweight Java class that represents a persistent data object. Entities are used to map Java objects to database tables, where each entity corresponds to a row in the table.

Entities are defined using annotations, which provide metadata about how the entity should be persisted and how it relates to other entities in the application. The most commonly used annotation for defining entities is @Entity, which marks a Java class as an entity. Entities typically have instance variables that correspond to columns in the database table, and methods that provide access to these variables. JPA also provides annotations for defining relationships between entities, such as @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany.

Entities can be persisted in the database using the JPA “EntityManager” interface, which provides methods for creating, reading, updating, and deleting entities. When an entity is persisted, JPA creates a corresponding row in the database table, and when an entity is read from the database, JPA populates the entity's instance variables with the corresponding column values.

In this diagram, the Entity represents a persistent data object, which is defined using fields and methods. Each field corresponds to a column in the database table, and each method provides access to these fields. The Id field is typically annotated with @Id annotation to indicate that it is the primary key for the entity.

18. Can you tell the difference between JPA and Hibernate?

  • JPA (Java Persistence API) is a specification for ORM (Object-Relational Mapping) in Java, while Hibernate is an implementation of JPA.
  • In other words, JPA provides a standard set of interfaces and annotations for ORM, while Hibernate is a concrete implementation of those interfaces and annotations.

You can find More Differences listed here - JPA vs Hibernate

19. What are some benefits of using an ORM framework like JPA?

Using an Object-Relational Mapping (ORM) framework like JPA (Java Persistence API) has several benefits. Some of them are:

  • Increased Productivity: JPA provides a high level of abstraction that allows developers to focus on business logic instead of writing SQL queries. This can lead to faster development cycles and fewer errors.
  • Portability: JPA abstracts away the details of the underlying database, which makes it possible to switch databases without changing the application code. This can save a lot of time and effort when porting applications between different databases.
  • Scalability: JPA provides a caching mechanism that can help improve application performance by reducing the number of database queries needed to access data. This can help an application scale better as the number of users and amount of data grows.
  • Maintainability: JPA provides a clear separation between application logic and persistence logic. This makes it easier to maintain and modify an application over time.
  • Standardization: JPA is a Java EE standard, which means that it is widely adopted and supported by many different vendors. This helps ensure that the application code is portable and compatible with a wide range of different platforms.

20. What is ORM Framework and how is JPA related to that?

An Object-Relational Mapping (ORM) framework is a software tool that allows developers to map object-oriented programming language constructs to relational database constructs. It provides a layer of abstraction between the application code and the database, allowing developers to work with objects and classes rather than SQL queries.

JPA (Java Persistence API) is a Java EE standard that provides an ORM framework for mapping Java objects to relational databases. It defines a set of interfaces and annotations that allow developers to create persistent entities, query data, and manage relationships between entities.

JPA is built on top of the Java Persistence Architecture (JPA), which is a standard for managing persistence in Java applications. JPA provides a set of standard interfaces and annotations that can be used with any JPA-compliant ORM framework.

In this diagram, the ORM Framework provides a set of interfaces and annotations that allow developers to map Java objects to relational databases. JPA implementation interacts with the Relational DB and uses ORM Framework to map Java objects to the database.

JPA Interview Questions for Experienced

1. What is the difference between CascadeType.ALL and CascadeType.PERSIST in JPA?

CascadeType.ALL CascadeType.PERSIST
Cascades all operations: ‘persist’, ‘merge’, ‘remove’, and ‘refresh’. Cascades only the ‘persist’ operation.
If an entity is associated with another entity using CascadeType.ALL, any operation performed on the parent entity will be propagated to the child entity. For example, if we delete a parent entity, any child entities associated with it will also be deleted. If an entity is associated with another entity using CascadeType.PERSIST, only the ‘persist’ operation will be propagated to the child entity. For example, if we persist a parent entity, any child entities associated with it will also be persisted, but any subsequent operations (e.g. remove or merge) will not be propagated.
CascadeType.ALL should be used with caution as it can result in unintended consequences, such as deleting child entities that should not be deleted. CascadeType.PERSIST is less risky as it only propagates the ‘persist’ operation, but it may require additional operations (such as ‘remove’ or ‘merge’) to ‘update’ or ‘delete’ child entities.

Conclusion

In conclusion, JPA (Java Persistence API) is a powerful tool for developers working with Java applications that need to interact with databases. As such, it's become an increasingly popular topic in interviews for Java development positions.

We hope that this article has provided you with a solid foundation for preparing for JPA interviews. By reviewing these questions and practising your answers, you can increase your chances of success and impress potential employers with your JPA expertise.

Remember, JPA is just one aspect of Java development, so be sure to also brush up on other relevant technologies and concepts. With a well-rounded understanding of Java development and JPA in particular, you'll be well-positioned to excel in your career. Also, if you are a java developer then other things related to java like Spring, Hibernate, etc content you can find here -

2. Explain the difference between a shared cache mode and a local cache mode in JPA? What are the advantages and disadvantages of each?

In JPA, there are two cache modes: 

  1. Shared cache mode allows multiple ‘EntityManager’ instances to share the same cache. This means that if one ‘EntityManager’ instance loads an entity from the database and stores it in the cache, another ‘EntityManager’ instance can retrieve the same entity from the cache without having to hit the database. The shared cache is managed by the JPA provider and is typically implemented using a second-level cache. The advantage of shared cache mode is that it can improve application performance by reducing the number of database queries. However, the disadvantage is that it can lead to consistency issues if the cache is not properly managed.
  2. Local cache mode, on the other hand, is specific to a single EntityManager’ instance. When an entity is loaded from the database using an ‘EntityManager’ in local cache mode, it is stored in the local cache of that ‘EntityManager’ instance. Subsequent requests for the same entity within that ‘EntityManager’ instance will be retrieved from the local cache instead of hitting the database. The advantage of local cache mode is that it provides greater control over the caching process and avoids potential consistency issues. However, the disadvantage is that it can lead to increased memory usage and slower performance if large numbers of entities are cached.

In general, the choice between shared and local cache mode depends on the specific requirements of the application. If the application requires high performance and can tolerate some consistency issues, shared cache mode may be a good choice. If the application requires greater control over the caching process and cannot tolerate consistency issues, local cache mode may be a better choice.

3. Can you explain how JPA handles entity state transitions (e.g. from new to managed, managed to remove, etc.)? What are some best practices for managing entity states in JPA?

JPA manages the state of entities as they are created, modified, and deleted in the application. The state of an entity can be one of the following:

  1. New: When an entity is first created using the new operator, it's in a new state.
  2. Managed: Once an entity is persisted using the EntityManager.persist() method, it enters the managed state. Entities in this state are managed by the persistence context, and any changes made to the entity are tracked and automatically synchronized with the database.
  3. Detached: Entities become detached when they are removed from the persistence context or when the persistence context is closed. In this state, changes made to the entity are not tracked or synchronized with the database. However, they can be re-attached to the persistence context later using the EntityManager.merge() method.
  4. Removed: When an entity is removed using the EntityManager.remove() method, it enters the removed state. Entities in this state are scheduled for deletion from the database when the transaction is committed.

To manage entity states in JPA, it's important to follow some best practices:

  1. Always use EntityManager to create, retrieve, update, and delete entities.
  2. Use the EntityManager.persist() method to create new entities.
  3. Use the EntityManager.merge() method to update existing entities or to re-attach detached entities to the persistence context.
  4. Use the EntityManager.remove() method to delete entities.
  5. Avoid using the new operator to create entities once JPA is involved in your application.
  6. Be aware of the transaction boundaries and make sure that all database operations are performed within a transaction.
  7. Keep the persistence context as small as possible to avoid unnecessary memory usage and performance issues.
  8. By following these best practices, you can ensure that entity state transitions are properly managed in your application and that your data is consistent and up-to-date in the database.

4. What types of identifier generation does JPA support?

JPA provides several strategies for generating unique identifiers for entity objects. Here are the different types of identifier generation supported by JPA:

  1. GenerationType.AUTO: This is the default strategy, and the choice of strategy is determined by the JPA provider. The strategy may be GenerationType.IDENTITY, GenerationType.SEQUENCE, or GenerationType.TABLE.
  2. GenerationType.IDENTITY: This strategy uses an auto-incremented database column to generate unique identifier values. This is only supported for databases that have auto-increment columns, such as MySQL, PostgreSQL, and SQL Server.
  3. GenerationType.SEQUENCE: This strategy uses a database sequence to generate unique identifier values. The database must support sequences, and the sequence must be defined in the database. This strategy is useful when the database doesn't support auto-increment columns, or when you want to generate unique identifiers before inserting the entity object into the database.
  4. GenerationType.TABLE: This strategy uses a separate database table to generate unique identifier values. Each time an identifier is needed, a row is inserted into the table, and the identifier value is obtained from the inserted row. This strategy is useful when the database doesn't support sequences or auto-increment columns, or when you want to generate unique identifiers outside of the database.
  5. GenerationType.IDENTITY: This strategy uses a user-defined algorithm to generate unique identifier values. You can define your own identifier generation strategy by implementing the “javax.persistence.spi.IdGenerator” interface.

5. What is the purpose of the @OneToOne and @OneToMany annotations in JPA? Explain in detail with examples.

In JPA, @OneToOne and @OneToMany are two annotations used to specify the type of relationship between two entities.

@OneToOne is used to specify a one-to-one relationship between two entities. It is typically used when one entity has a single associated entity of another type and vice versa.

For example, let's consider two entities, Employee and Address, where an employee can have only one address and an address can be associated with only one employee. In this scenario, the Employee entity would have a field annotated with @OneToOne that references the Address entity, and the Address entity would have a field annotated with @OneToOne that references the Employee entity.

Let's look at the snippets of this example:

@Entity
public class Employee {
    @Id
    @GeneratedValue
    private Long id;

    @OneToOne(mappedBy="employee")
    private Address address;
    
    // other fields and methods
}

@Entity
public class Address {
    @Id
    @GeneratedValue
    private Long id;

    @OneToOne
    @JoinColumn(name="employee_id")
    private Employee employee;
    
    // other fields and methods
}

@OneToMany is used to specify a one-to-many relationship between two entities. It is typically used when one entity has multiple associated entities of another type, and the associated entities only have a single association back to the original entity.

For example, let's consider two entities, Department and Employee, where a department can have multiple employees, but an employee can belong to only one department. In this scenario, the Department entity would have a collection field annotated with @OneToMany that references the Employee entity.

Let's look at the snippet for this example:

@Entity
public class Department {
    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(mappedBy="department")
    private List<Employee> employees;
    
    // other fields and methods
}

@Entity
public class Employee {
    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    @JoinColumn(name="department_id")
    private Department department;
    
    // other fields and methods
}

In this example, the @OneToMany annotation is used to specify that the Department entity has a one-to-many relationship with the Employee entity. The mappedBy attribute is used to indicate that the relationship is mapped by the department field in the Employee entity.

6. How can you use JPA to handle optimistic concurrency control? Can you explain how the EntityManager.lock() method works?

JPA provides a mechanism for optimistic concurrency control to handle situations where multiple transactions are trying to modify the same entity concurrently. In optimistic concurrency control, each transaction checks to see if any other transaction has modified the entity since it was last read. This is achieved by using a version field in the entity, which is incremented each time the entity is modified.

JPA provides the @Version annotation to indicate which field in the entity should be used as the version field. When an entity is persisted or updated, JPA automatically checks the current version of the entity in the database and compares it with the version in the entity being persisted or updated. If the versions do not match, a “javax.persistence.OptimisticLockException” is thrown, indicating that the entity has been modified by another transaction.

In addition to the automatic optimistic locking provided by JPA, the EntityManager interface provides a lock() method that allows you to manually acquire a lock on an entity to prevent other transactions from modifying it until the lock is released.

The EntityManager.lock() method allows you to specify the lock mode to use and the timeout for the lock. The lock mode can be either optimistic or pessimistic. With optimistic locking, the lock is released immediately after the transaction completes. With pessimistic locking, the lock is held until the transaction completes or the lock timeout expires.

Here's an example of using the EntityManager.lock() method to acquire an optimistic lock on an entity:

EntityManager em = ... // obtain the EntityManager
em.getTransaction().begin();

// find the entity to update
MyEntity entity = em.find(MyEntity.class, entityId);

// acquire an optimistic lock on the entity
em.lock(entity, LockModeType.OPTIMISTIC);

// modify the entity
entity.setSomeField(newValue);

em.getTransaction().commit();

In this example, the EntityManager finds the entity to update and acquires an optimistic lock on it using the lock() method. The entity is then modified and the transaction is committed. If another transaction has modified the entity in the meantime, an OptimisticLockException will be thrown when the transaction tries to commit the changes.

7. How would you implement a custom JPA entity listener? Can you give an example of when you might use a custom entity listener in your application?

To implement a custom JPA entity listener, we need to create a class that implements one of the JPA entity listeners interfaces : EntityListener or EntityCallback. 

You can then annotate the entity class or the entity listener class with the @EntityListeners annotation to register the listener.

Consider the below example of a custom JPA entity listener:

public class UserListener {
    @PrePersist
    public void prePersist(User user) {
        user.setCreationDate(new Date());
    }
}

In this example, we have a UserListener class with a prePersist method that sets the creation date of a user before it's persisted to the database. We can then annotate the User entity with the @EntityListeners annotation to register the listener:

@Entity
@Table(name = "users")
@EntityListeners(UserListener.class)
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;

    private String password;

    @Temporal(TemporalType.TIMESTAMP)
    private Date creationDate;

    // getters and setters
}

In this example, we have a User entity with an id, a username, a password, and a creation date field. We annotate the entity with @EntityListeners and specify the UserListener class to register the listener.

We can use a custom entity listener in our application for various purposes, such as auditing, validation, or processing entity lifecycle events. For example, we could use a custom listener to calculate and update the average rating of a product when a new review is added or to validate that a user has a unique email address before it's persisted in the database, etc.

8. How can you use JPA to perform pagination of query results? What are the advantages of using pagination over fetching all results at once?

JPA provides support for the pagination of query results through the use of the setFirstResult and setMaxResults methods of the Query interface.

Consider the below code to understand how to use pagination with JPA:

EntityManager em = entityManagerFactory.createEntityManager();
Query query = em.createQuery("SELECT e FROM Employee e ORDER BY e.name");
query.setFirstResult(0); // Starting index of the results to return
query.setMaxResults(10); // Maximum number of results to return
List<Employee> employees = query.getResultList();
em.close();

In this example, we have created a query to select all employees and order them by name. We then set the starting index of the results to 0 and the maximum number of results to 10 using the setFirstResult() and setMaxResults() methods. Finally, we execute the query and retrieve the results using getResultList().

The advantages of using pagination over fetching all results at once include:

  1. Reduced memory usage: When fetching a large number of results, it can consume a lot of memory to hold all the results in memory at once. Pagination allows you to retrieve a smaller subset of results at a time, reducing memory usage.
  2. Faster response times: If a query returns a large number of results, it can take a long time to return all the results. Pagination allows you to retrieve smaller subsets of results, which can improve response times.
  3. Improved user experience: If you're displaying query results to users, it can be overwhelming to display a large number of results at once. Pagination allows you to display a smaller subset of results at a time, making it easier for users to navigate through the results.
  4. Better performance: When using pagination, the database can use more efficient algorithms to retrieve and sort smaller subsets of results. This can result in better performance than fetching all results at once.

9. What is the purpose of the @Version annotation in JPA? How is it used in optimistic locking? Explain the concept in detail.

The purpose of the @Version annotation in JPA is to define a version field on an entity that can be used for optimistic locking.

When an entity is updated in JPA, the persistence provider checks whether the version of the entity in the database matches the version of the entity in the persistence context. If the versions match, JPA updates the entity and increments the version number. If the versions do not match, it means that another transaction has modified the entity in the meantime, and JPA throws an optimistic locking exception.

The @Version annotation is used to mark a field on an entity as the version field. This field should be an integer or a timestamp type. When an entity is updated, JPA automatically increments the version number or updates the timestamp value.

Let’s understand this with the help of the below snippet:

@Entity
public class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String title;
    private String author;
    private double price;
    
    @Version
    private int version;
    
    // getters and setters
}

In this example, we have a Book entity with an id, a title, an author, a price, and a version field annotated with @Version. The version field is an integer that JPA uses for optimistic locking.

When an entity is updated, JPA checks whether the version of the entity in the database matches the version of the entity in the persistence context. If the versions match, JPA updates the entity and increments the version number. If the versions do not match, JPA throws an optimistic locking exception.

The @Version annotation can be applied to only one field per entity class. If the entity has more than one field that needs to be used for optimistic locking, you can create a composite version field using an embedded object or a concatenated string.

10. How does JPA handle optimistic locking? Can you give an example of how you would implement optimistic locking in JPA?

JPA (Java Persistence API) provides support for optimistic locking through the use of version fields. Optimistic locking is a concurrency control mechanism that allows multiple transactions to access the same data concurrently while ensuring data consistency.

In JPA, optimistic locking is implemented by defining a version field on the entity class. This version field is automatically incremented by the persistence provider each time an entity is updated. When an entity is updated, JPA checks if the version of the entity in the database matches the version of the entity in the persistence context. If the versions do not match, it means that another transaction has modified the entity in the meantime, and JPA throws an optimistic locking exception.

Consider the below snippets for the implementation of optimistic locking in JPA:

@Entity
public class Employee {
    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @Version
    private int version;

    // getters and setters
}

In this example, we have an Employee entity with an id, a name, and a version field annotated with @Version. The version field is an integer that JPA uses for optimistic locking.

Now let's say we want to update an employee's name:

EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();

Employee employee = em.find(Employee.class, 1L);
employee.setName("John Doe");

em.getTransaction().commit();
em.close();


When we call em.getTransaction().commit(), JPA checks the version of the employee entity in the database against the version of the employee entity in the persistence context. If the versions match, JPA updates the entity and increments the version number. If the versions do not match, JPA throws an optimistic locking exception.

11. Explain in detail the JPA application life cycle?

The lifecycle of a JPA application can be divided into several stages, each with its own set of actions and interactions between the various components involved. These stages are:

  • Entity Class Creation: The first stage in the lifecycle of a JPA application is the creation of entity classes. Entity classes are Java classes that represent database tables and have properties that correspond to columns in those tables.
  • Entity Mapping: The next stage is entity mapping, which involves defining the mapping between the entity classes and the database tables. This is typically done using annotations or XML configuration files, and it specifies how the properties of the entity classes correspond to the columns in the database tables.
  • Persistence Unit Creation: The third stage is the creation of a Persistence Unit, which is a logical grouping of one or more entity classes and their associated metadata. This is typically done using a persistence.xml file, which specifies the database connection details, the list of entity classes to be managed, and any additional configuration options.
  • EntityManagerFactory Creation: The next stage is the creation of an EntityManagerFactory, which is responsible for creating EntityManager instances. The EntityManagerFactory is typically created once at the start of the application and is used to create EntityManager instances throughout the application.
  • EntityManager Creation: The next stage is the creation of an EntityManager, which provides the primary interface for interacting with the Persistence Context. The EntityManager is responsible for managing the lifecycle of entity objects, executing queries, and performing CRUD operations on the database.
  • Transaction Management: The next stage is transaction management, which involves defining the boundaries of transactions and managing their lifecycle. Transactions are used to ensure data consistency and integrity, and they are typically managed using annotations or programmatic APIs.
  • Entity Lifecycle Management: The next stage is entity lifecycle management, which involves managing the lifecycle of entity objects within the Persistence Context. Entity objects can be in one of several states, including New, Managed, Detached, and Removed, and their state can be changed using the EntityManager API.
  • Query Execution: The final stage is query execution, which involves executing JPQL queries to retrieve data from the database. JPQL is a query language that is similar to SQL but is specific to JPA.

Note: This is a simplified view of the JPA lifecycle and there may be additional stages or variations depending on the specific implementation and configuration of the application.

JPA MCQ Questions

1.

Which of the following is true about a JPA entity's default fetch strategy?

2.

Which of the following methods is used to persist an entity to the database using JPA?

3.

Which of the following is used to specify the order in which results should be returned in a JPA query?

4.

Which of the following is used to specify the inheritance strategy for a JPA entity hierarchy?

5.

Which of the following is used to specify the fetch strategy for a JPA relationship?

6.

Which of the following is used to specify a relationship between two JPA entities?

7.

Which of the following is used to specify a named query in JPA?

8.

Which of the following is used to specify a discriminator column in a JPA inheritance hierarchy?

9.

Which of the following is used to configure the JPA persistence unit in the persistence.xml file?

10.

Which of the following is true about JPA transactions?

11.

What is the purpose of the @JoinColumn annotation in JPA?

12.

Which of the following is not a valid JPA entity state?

13.

Which of the following is not a valid JPA entity association type?

14.

Which of the following is not a JPA transaction isolation level?

15.

Which of the following is not a JPA query language?

16.

Which of the following annotations is used to mark an entity as persistent?

17.

Which of the following annotations is used to mark a field as the primary key of an entity?

18.

What is the purpose of the EntityManagerFactory in JPA?

19.

What is the purpose of the EntityManager in JPA?

20.

What is the purpose of the CascadeType.ALL option in JPA?

Excel at your interview with Masterclasses Know More
Certificate included
What will you Learn?
Free Mock Assessment
Fill up the details for personalised experience.
Phone Number *
OTP will be sent to this number for verification
+91 *
+91
Change Number
Graduation Year *
Graduation Year *
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
*Enter the expected year of graduation if you're student
Current Employer
Company Name
College you graduated from
College/University Name
Job Title
Job Title
Engineering Leadership
Software Development Engineer (Backend)
Software Development Engineer (Frontend)
Software Development Engineer (Full Stack)
Data Scientist
Android Engineer
iOS Engineer
Devops Engineer
Support Engineer
Research Engineer
Engineering Intern
QA Engineer
Co-founder
SDET
Product Manager
Product Designer
Backend Architect
Program Manager
Release Engineer
Security Leadership
Database Administrator
Data Analyst
Data Engineer
Non Coder
Other
Please verify your phone number
Edit
Resend OTP
By clicking on Start Test, I agree to be contacted by Scaler in the future.
Already have an account? Log in
Free Mock Assessment
Instructions from Interviewbit
Start Test