JPA (Java Persistence API) Interview Questions

This section covers frequently asked JPA interview questions, focusing on core concepts, entity management, and different types of mappings.

What is the Java Persistence API (JPA)?

JPA is a Java specification for managing persistence—storing and retrieving data—between Java objects and relational databases. It simplifies database interactions by providing an object-oriented way to work with relational data. JPA itself is a specification; it requires an implementation (like Hibernate, EclipseLink, or DataNucleus) to actually interact with a database.

JPA's Role in Data Management

JPA itself doesn't directly access or manage data; it's a specification. ORM (Object-Relational Mapping) tools implement the JPA specification, providing the actual data access capabilities.

Object-Relational Mapping (ORM)

ORM is a programming technique that maps objects in your code to tables in a relational database. It simplifies database interactions by allowing you to work with objects instead of writing SQL queries directly. This improves code readability and maintainability.

Advantages of JPA

  • Simplified database access (less code).
  • Improved code readability and maintainability.
  • Reduced boilerplate code (using annotations).
  • Portability (can switch between different JPA implementations).
  • Extensibility (ORM tools can add features to the standard JPA).

Embeddable Classes

Embeddable classes represent attributes of an entity but don't have their own unique identity. They're embedded within the entity class. For example, an Address class might be embeddable within a Person entity.

ORM Frameworks

  • Hibernate
  • EclipseLink (formerly TopLink)
  • OpenJPA
  • DataNucleus
  • Others...

JPQL (Java Persistence Query Language)

JPQL is JPA's query language. It's similar to SQL but operates on objects instead of database tables.

Persisting an Entity

  1. Create an EntityManagerFactory using Persistence.createEntityManagerFactory("persistenceUnitName").
  2. Obtain an EntityManager from the factory.
  3. Begin a transaction using em.getTransaction().begin().
  4. Persist the entity using em.persist(entity).
  5. Commit the transaction using em.getTransaction().commit().
  6. Close the EntityManager and EntityManagerFactory.

Inserting an Entity

[Include a complete code example demonstrating inserting an entity into a database using JPA. The example should include an entity class, a persistence unit definition (persistence.xml), and a main class that performs the insertion.]

Finding an Entity

Use the find() method of the EntityManager to retrieve an entity by its primary key.

[Include a complete code example demonstrating retrieving an entity from a database using JPA. The example should include an entity class, a persistence unit definition (persistence.xml), and a main class that performs the retrieval.]

Updating an Entity

[Include a complete code example demonstrating updating an entity in a database using JPA. The example should include an entity class, a persistence unit definition (persistence.xml), and a main class that performs the update.]

Deleting an Entity

The remove() method of EntityManager deletes an entity from the database.

[Include a complete code example demonstrating deleting an entity from a database using JPA. The example should include an entity class, a persistence unit definition (persistence.xml), and a main class that performs the deletion.]

Inserting a Record (Transactional)

[Provide code example illustrating a transactional approach to record insertion. Emphasize the use of the @Transactional annotation for managing the transaction.]

Entity Mapping Directions

  • Unidirectional: One entity maps to another (only one side maintains the relationship).
  • Bidirectional: Both entities maintain the relationship.

Types of Entity Mapping

  • One-to-one
  • One-to-many
  • Many-to-one
  • Many-to-many

Types of Entity Mappings

JPA supports various ways to map relationships between entities:

  • One-to-One: A single instance of one entity is associated with at most one instance of another entity.
  • One-to-Many: One instance of an entity is associated with multiple instances of another entity (often represented as a collection).
  • Many-to-One: Multiple instances of an entity can be associated with a single instance of another entity.
  • Many-to-Many: Multiple instances of one entity can be associated with multiple instances of another entity (typically implemented using a join table).

Orphan Removal

Orphan removal is a JPA feature for automatically removing entities from the database when they're no longer associated with their owning entity (in one-to-one or one-to-many relationships). The orphanRemoval = true attribute in the mapping can enable this behavior.

Persistence Lifecycle of an Object

A JPA-managed object goes through these states:

  • Transient: The object is newly created and not yet managed by the persistence context (not in the database).
  • Persistent: The object is managed by the persistence context (it has a corresponding row in the database).
  • Detached: The object was managed but is now detached from the persistence context (usually after the EntityManager is closed). Changes made to a detached object aren't automatically saved to the database.

Identifier Generation Strategies

JPA provides several ways to generate primary keys (identifiers) for entities using the @GeneratedValue annotation:

  • Auto: The persistence provider chooses the strategy.
  • Table: Uses a separate table to generate IDs.
  • Sequence: Uses a database sequence.
  • Identity: Relies on the database's auto-increment functionality.

Entities in JPA

An entity in JPA is a class representing a persistent object (stored in the database). Each entity class should have a primary key.

Properties of an Entity

  • Persistable: Can be stored and retrieved from the database.
  • Persistent Identity: Has a unique identifier (primary key).
  • Transactionality: Changes made to an entity are managed within database transactions.
  • Granularity: Entities should represent meaningful, independent units of data, not just primitive types.

Role of the EntityManager

The EntityManager is the central API for managing persistence in JPA. It provides methods for creating, reading, updating, and deleting entities.

Constraints on Entity Classes

  • Must have a no-argument constructor.
  • Cannot be final.
  • Must be annotated with @Entity.
  • Should implement Serializable (for detached objects).

Java Collections in JPA

JPA collections are used to map relationships where an entity is associated with a collection of other entities.

Objects Allowed in JPA Collections

  • Basic types (int, String, etc.)
  • Entities
  • Embeddable objects

Collection Types in JPA

  • List
  • Set
  • Map

Cascading Operations

Cascading operations propagate changes (persist, merge, detach, refresh, remove) from a parent entity to its related child entities.

JPA Cascade Types

  • PERSIST
  • MERGE
  • REMOVE
  • REFRESH
  • DETACH
  • ALL

JPQL (Java Persistence Query Language)

JPQL is JPA's object-oriented query language for querying entities. It's translated to SQL by the JPA provider.

JPQL Features

  • Simple and powerful syntax.
  • Platform-independent (works with various databases).
  • Can be used statically (in annotations) or dynamically.

Criteria API

The Criteria API provides a type-safe and portable way to build queries in Java. It's an alternative to JPQL, offering compile-time type checking.