Popular Searches
Popular Course Categories
Popular Courses

Introduction to Java Persistence API (JPA)

Introduction to Java Persistence API (JPA)

Spring Data JPA and Database Integration

Introduction to Java Persistence API (JPA)

Course: Advanced Java Training

Topic: Introduction to Java Persistence API (JPA)

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to Java Persistence API (JPA)

The Java Persistence API (JPA) is a Java specification that defines a standard way to map Java objects to relational database tables and manage persistent data. It allows developers to work with database records through Java objects rather than writing SQL statements for every database operation.

JPA is commonly used in enterprise applications built with Java, Spring Boot, and relational databases such as MySQL, PostgreSQL, and Oracle. It provides a consistent programming model for creating, retrieving, updating, and deleting persistent objects.

JPA is a specification, not a standalone database engine or implementation. Hibernate is a popular implementation of JPA. Other implementations are also available. Spring Data JPA builds on JPA and simplifies common database access tasks through repository interfaces.

Learning Objectives

  • Understand persistence and object-relational mapping.
  • Learn the purpose and architecture of JPA.
  • Understand entities, primary keys, and entity managers.
  • Configure JPA in a Spring Boot application.
  • Map Java classes to relational database tables.
  • Perform CRUD operations using JPA.
  • Understand entity lifecycle states and transactions.
  • Explore JPQL, relationships, and repository interfaces.
  • Identify common JPA errors and performance problems.

2. What Is Persistence?

Persistence refers to storing application data so that it remains available even after the application stops running. For example, when a user registers on a website, their details must be stored in a database so that the information can be retrieved later.

Without persistence, data stored only in application memory may be lost when the program terminates.

Example

Consider a Java application that manages student records. A Student object may contain an ID, name, and email address.

public class Student {
    private int id;
    private String name;
    private String email;
}

Persistence allows the application to save this information to a database table and retrieve it during a later request.

Why Is Persistence Important?

  • Stores information permanently in a database.
  • Allows records to be retrieved across application sessions.
  • Supports business applications such as banking, e-commerce, and student management.
  • Maintains structured data and relationships between records.
  • Supports transactional operations and data consistency.

3. What Is Object-Relational Mapping (ORM)?

Object-Relational Mapping (ORM) is a technique that maps object-oriented classes and their properties to relational database tables and columns.

Java applications use objects, classes, and relationships. Relational databases store data in tables, rows, and columns. ORM helps bridge this difference.

Java Object and Database Table Mapping

Java Concept Relational Database Concept
Class Table
Object Row or record
Field or property Column
Object identifier Primary key
Object relationship Foreign key or relationship mapping

Example

Consider a Java class named Employee:

public class Employee {
    private Long id;
    private String name;
    private double salary;
}

Its corresponding database table might look like this:

id name salary
1 Anita 45000.00
2 Rahul 52000.00

An ORM provider can map the Java properties to the corresponding database columns and translate supported persistence operations into SQL.

4. What Is JPA?

JPA defines standard interfaces, annotations, and rules for persisting Java objects in relational databases. It allows applications to use a consistent persistence model without depending directly on one ORM provider's proprietary API.

Key Features of JPA

  • Entity mapping: Maps Java classes to database tables.
  • Primary key management: Defines identifiers for persistent entities.
  • CRUD operations: Supports creating, reading, updating, and deleting records.
  • Query support: Provides JPQL and criteria-based querying.
  • Relationship mapping: Supports one-to-one, one-to-many, many-to-one, and many-to-many associations.
  • Transaction integration: Works with transactions to maintain data consistency.
  • Lifecycle management: Tracks the state of persistent entities.
  • Provider flexibility: Supports different implementations of the JPA specification.

5. JPA vs. JDBC vs. Hibernate vs. Spring Data JPA

These technologies are related, but they serve different roles in Java database applications.

Technology Type Main Responsibility
JDBC Java database connectivity API Connects to databases and executes SQL using connections, statements, and result sets.
JPA Persistence specification Defines standard object-relational persistence interfaces and behavior.
Hibernate ORM ORM implementation Implements JPA and provides additional ORM capabilities.
Spring Data JPA Spring data-access framework Reduces repository boilerplate and simplifies common JPA operations.

5.1 JDBC Example

With JDBC, developers commonly write SQL statements and handle result sets directly.

String sql = "SELECT id, name FROM students WHERE id = ?";

try (PreparedStatement statement =
         connection.prepareStatement(sql)) {

    statement.setLong(1, 101L);

    try (ResultSet resultSet = statement.executeQuery()) {
        if (resultSet.next()) {
            String name = resultSet.getString("name");
            System.out.println(name);
        }
    }
}

5.2 JPA Approach

With JPA, developers can retrieve an entity through an entity manager:

Student student = entityManager.find(Student.class, 101L);

The persistence provider generates and executes the required SQL according to the entity mapping and runtime configuration.

6. Understanding JPA Architecture

JPA architecture consists of application code, JPA interfaces, a persistence provider, a persistence context, transaction management, and the underlying database.

Main Components

  • Entity: A Java class whose instances represent persistent data.
  • EntityManager: Provides operations for managing entity instances.
  • Persistence Context: Tracks managed entity instances and their changes.
  • EntityManagerFactory: Creates EntityManager instances.
  • Persistence Provider: Implements the JPA specification, such as Hibernate.
  • Transaction: Groups database operations into a unit of work.
  • Database: Stores persistent records in tables and related structures.

Basic Architecture Flow

Java Application
       |
       v
JPA Interfaces and Annotations
       |
       v
Persistence Provider (e.g., Hibernate)
       |
       v
JDBC / Database Driver
       |
       v
Relational Database

When an application saves or retrieves an entity, the persistence provider interprets the mapping metadata and performs the necessary database operations.

7. What Is a JPA Entity?

An entity is a Java class mapped to a database table. Each persistent entity instance generally represents a row in that table.

The @Entity annotation marks a class as a JPA entity. A typical entity also defines a primary key using @Id.

Example: Student Entity

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "students")
public class Student {

    @Id
    private Long id;

    private String name;
    private String email;

    public Student() {
    }

    public Student(Long id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

This example uses Jakarta Persistence imports, as used in modern Spring Boot 3 and later applications. Older JPA-based applications may use the javax.persistence namespace instead.

Important Entity Annotations

Annotation Purpose
@Entity Declares the class as a persistent entity.
@Table Specifies the database table name and related table mapping options.
@Id Identifies the primary key property or field.
@GeneratedValue Configures identifier generation.
@Column Customizes column mapping.
@Transient Marks a field or property that should not be persisted as a database attribute.
@Enumerated Specifies how an enum is stored.
@Temporal Supports mapping legacy Date and Calendar values; it is not needed for modern java.time types.

8. Primary Keys and Identifier Generation

Every JPA entity must have an identifier. The identifier allows the persistence provider to distinguish one entity instance from another.

8.1 Using @Id

@Entity
public class Department {

    @Id
    private Long id;

    private String departmentName;

    public Department() {
    }
}

In this example, the application must supply the identifier unless another generation strategy is configured.

8.2 Using @GeneratedValue

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String departmentName;

    public Department() {
    }

    public Department(String departmentName) {
        this.departmentName = departmentName;
    }

    public Long getId() {
        return id;
    }

    public String getDepartmentName() {
        return departmentName;
    }
}

GenerationType.IDENTITY commonly uses an identity column generated by the database. Other strategies include AUTO, SEQUENCE, and TABLE. The appropriate choice depends on the database, provider, and application requirements.

9. Mapping Java Classes to Database Tables

JPA uses annotations or XML mapping metadata to define how entity attributes correspond to database columns.

9.1 Custom Table and Column Names

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "employee_records")
public class Employee {

    @Id
    private Long id;

    @Column(name = "employee_name", nullable = false, length = 100)
    private String name;

    @Column(name = "employee_email", unique = true)
    private String email;

    public Employee() {
    }
}

The table and column names in the database can differ from the Java class and property names. Column options such as nullability and uniqueness also help express mapping constraints, though database schema constraints must be created and maintained appropriately.

10. Setting Up JPA in Spring Boot

Spring Boot simplifies JPA configuration through auto-configuration. A typical project needs Spring Data JPA, a database driver, and database connection settings.

10.1 Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

Use a compatible Spring Boot dependency-management configuration rather than independently selecting versions for the starter and database driver.

10.2 Database Configuration

Example configuration in application.properties for a local MySQL database:

spring.datasource.url=jdbc:mysql://localhost:3306/college_db
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

Set the database credentials through environment variables or a secure secrets-management system. Do not commit real passwords to source control.

Important: The setting spring.jpa.hibernate.ddl-auto=update is useful for learning and certain development environments, but production applications should use a controlled schema migration strategy such as Flyway or Liquibase. Avoid exposing SQL output in production logs if it could reveal sensitive information.

11. Understanding EntityManager

The EntityManager is a central JPA interface used to manage entities within a persistence context. It provides methods for finding, persisting, merging, removing, and querying entities.

Common EntityManager Methods

Method Purpose
persist() Makes a new entity managed so that it can be inserted into the database.
find() Retrieves an entity by its primary key, returning null when it is not found.
merge() Copies state from a new or detached entity into a managed entity and returns the managed instance.
remove() Marks a managed entity for deletion.
flush() Synchronizes pending persistence-context changes with the database.
refresh() Reloads a managed entity's state from the database.
createQuery() Creates a query, commonly using JPQL or the Criteria API.

Example Using EntityManager

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class StudentDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    public void save(Student student) {
        entityManager.persist(student);
    }

    @Transactional(readOnly = true)
    public Student findById(Long id) {
        return entityManager.find(Student.class, id);
    }
}

In a Spring-managed application, the container supplies the EntityManager proxy. Transaction boundaries should be defined appropriately, usually at the service layer for business operations involving one or more repositories.

12. Understanding the Persistence Context

The persistence context is the environment in which JPA tracks managed entity instances. It helps maintain identity within the context and detects changes made to managed entities.

For example, if an entity is retrieved and its name is changed inside a transaction, JPA can detect the modification and synchronize the updated value with the database during flushing or transaction completion.

Example: Updating a Managed Entity

@Transactional
public void updateStudentName(Long id, String newName) {
    Student student = entityManager.find(Student.class, id);

    if (student != null) {
        student.setName(newName);
    }
}

No explicit update method is required in this example. The entity is managed, so the persistence provider can detect the changed property and update the database when the persistence context is flushed within the transaction.

13. Entity Lifecycle States

JPA entities move through different lifecycle states depending on how they are created, persisted, detached, and removed.

State Description
New / Transient The object exists in Java memory but is not yet managed by a persistence context.
Managed / Persistent The persistence context tracks the entity and detects its changes.
Detached The entity has an identifier but is no longer managed by the current persistence context.
Removed The managed entity has been marked for deletion.

Lifecycle Example

Student student = new Student();
student.setId(101L);
student.setName("Rahul");

// New / transient state
entityManager.persist(student);

// Managed state
student.setName("Rahul Sharma");

// Marked for removal
entityManager.remove(student);

These operations must be performed with an appropriately managed EntityManager and transaction. After an entity is removed, the pending deletion is synchronized with the database during flushing or transaction completion.

14. CRUD Operations in JPA

CRUD stands for Create, Read, Update, and Delete. These are the fundamental operations used to manage persistent records.

14.1 Create

@Transactional
public void createStudent(Student student) {
    entityManager.persist(student);
}

The persist() method makes a new entity managed. The insert may be executed during a flush or earlier when required by the provider or identifier-generation strategy.

14.2 Read

@Transactional(readOnly = true)
public Student getStudent(Long id) {
    return entityManager.find(Student.class, id);
}

14.3 Update

@Transactional
public void updateStudent(Long id, String name) {
    Student student = entityManager.find(Student.class, id);

    if (student != null) {
        student.setName(name);
    }
}

Changes to managed entities are detected by dirty checking. For detached entities, merge() may be appropriate, but the returned managed instance should be used for subsequent managed operations.

14.4 Delete

@Transactional
public void deleteStudent(Long id) {
    Student student = entityManager.find(Student.class, id);

    if (student != null) {
        entityManager.remove(student);
    }
}

Checking for null prevents the application from attempting to remove a missing entity. A service or controller can translate the missing-record outcome into an appropriate API response, such as 404 Not Found.

15. Introduction to Spring Data JPA

Spring Data JPA is a Spring project that simplifies database access by providing repository abstractions on top of JPA. It reduces repetitive DAO code and provides common CRUD operations through repository interfaces.

Instead of implementing every database operation manually, developers can define an interface extending JpaRepository.

15.1 Creating a Repository

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

public interface StudentRepository
        extends JpaRepository<Student, Long> {
}

The first generic type is the entity class, and the second is the primary key type.

15.2 Common Repository Methods

Method Purpose
save(entity) Saves a new or existing entity according to repository and entity state.
findById(id) Retrieves an entity by ID as an Optional.
findAll() Retrieves all matching entities, subject to the method and repository configuration.
existsById(id) Checks whether an entity with the given ID exists.
deleteById(id) Deletes the entity with the specified ID if present according to repository semantics.
count() Returns the number of entities.

16. Creating a Service Layer

The service layer contains business logic and coordinates repository operations. Separating service logic from controllers makes applications easier to test and maintain.

import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class StudentService {

    private final StudentRepository repository;

    public StudentService(StudentRepository repository) {
        this.repository = repository;
    }

    public Student create(Student student) {
        return repository.save(student);
    }

    @Transactional(readOnly = true)
    public Optional<Student> findById(Long id) {
        return repository.findById(id);
    }

    @Transactional(readOnly = true)
    public List<Student> findAll() {
        return repository.findAll();
    }

    public Student update(Long id, Student input) {
        Student student = repository.findById(id)
            .orElseThrow(() ->
                new IllegalArgumentException("Student not found"));

        student.setName(input.getName());
        student.setEmail(input.getEmail());

        return repository.save(student);
    }

    public void delete(Long id) {
        repository.deleteById(id);
    }
}

This example demonstrates the service pattern. In a production API, use a domain-specific exception for missing records, validate inputs, and ensure update operations only modify fields that clients are allowed to change.

17. Creating a REST Controller with Spring Data JPA

A REST controller exposes HTTP endpoints and delegates business operations to the service layer.

import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/students")
public class StudentController {

    private final StudentService service;

    public StudentController(StudentService service) {
        this.service = service;
    }

    @PostMapping
    public ResponseEntity<Student> create(
            @RequestBody Student student) {
        Student saved = service.create(student);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(saved);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Student> getById(
            @PathVariable Long id) {
        return service.findById(id)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @GetMapping
    public List<Student> getAll() {
        return service.findAll();
    }

    @PutMapping("/{id}")
    public ResponseEntity<Student> update(
            @PathVariable Long id,
            @RequestBody Student student) {
        return ResponseEntity.ok(service.update(id, student));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(
            @PathVariable Long id) {
        service.delete(id);
        return ResponseEntity.noContent().build();
    }
}

This is a learning example, not a complete production-ready API. A production implementation should use request and response DTOs, validation, controlled exception handling, and a clearly defined policy for missing records and duplicate requests. For reliable updates, load the existing entity and update allowed fields rather than blindly trusting an incoming persistence entity.

18. Understanding JPQL

Java Persistence Query Language (JPQL) is an object-oriented query language used to query entities and their properties rather than directly querying database tables and columns.

JPQL is similar to SQL in structure, but it uses entity names and Java entity attributes. The persistence provider translates JPQL into database-specific SQL.

18.1 Example JPQL Query

import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import java.util.List;

TypedQuery<Student> query = entityManager.createQuery(
    "SELECT s FROM Student s WHERE s.name = :name",
    Student.class
);

query.setParameter("name", "Rahul");

List<Student> students = query.getResultList();

The query uses the entity name Student and the entity property name. Named parameters help keep query values separate from query text and prevent SQL injection through properly bound values.

18.2 Querying with Spring Data JPA

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository
        extends JpaRepository<Student, Long> {

    List<Student> findByName(String name);
}

Spring Data JPA can derive a query from a repository method name when the method follows supported naming conventions.

19. Understanding Entity Relationships

Real-world applications often contain relationships between entities. JPA provides annotations to represent these relationships in the object model.

Relationship Description Example
@OneToOne One entity is associated with one other entity. User and profile
@OneToMany One entity is associated with multiple entities. Department and employees
@ManyToOne Multiple entities can refer to one entity. Many employees belong to one department
@ManyToMany Multiple entities can be associated with multiple other entities. Students and courses

Example: Many-to-One Relationship

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;

@Entity
public class Employee {

    @Id
    private Long id;

    private String name;

    @ManyToOne
    private Department department;

    public Employee() {
    }
}

Multiple employee records can refer to the same department. For production mappings, configure the relationship's foreign key, fetch strategy, cascade behavior, and JSON representation deliberately.

20. Transactions in JPA

A transaction groups database operations into a unit of work. Transactions help preserve consistency when multiple related operations must succeed or fail together.

Spring applications commonly use @Transactional to define transaction boundaries.

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EnrollmentService {

    @Transactional
    public void enrollStudent() {
        // Save enrollment details.
        // Update related records.
        // Both operations should participate
        // in the same transaction.
    }
}

Transaction behavior depends on the configured transaction manager, propagation settings, and exception handling. By default, Spring rolls back on unchecked exceptions and errors; checked exceptions generally require explicit rollback configuration if rollback is desired.

21. Lazy Loading and Eager Loading

Fetch strategies determine when related entity data is loaded.

  • Lazy loading: Related data is loaded when accessed, subject to the persistence context and provider behavior.
  • Eager loading: Related data is required to be fetched eagerly, although the provider may use different SQL strategies to obtain it.

Lazy loading can improve efficiency when relationships are not needed. However, accessing lazy properties outside an open persistence context may cause a lazy-initialization error. Eager loading can retrieve more data than necessary and may create performance issues.

Use suitable fetch joins, entity graphs, projections, or DTO queries when the application needs to control which data is retrieved.

22. Common JPA Errors and Troubleshooting

Error or Problem Possible Cause Solution
Entity is not mapped The class is not registered or lacks valid entity mapping Check @Entity, package scanning, and persistence configuration.
Missing identifier No primary key is defined Define an identifier using @Id.
Database connection failure Incorrect URL, credentials, driver, or database availability Verify connection settings and database status.
Transient property error A related entity has not been persisted or cascade behavior is incorrect Persist related entities or configure cascade operations carefully.
Lazy initialization exception Lazy data is accessed after the persistence context is closed Fetch required data within the appropriate transaction or map it to a DTO.
Duplicate key error An identifier or unique value already exists Review ID generation and uniqueness constraints.
Unexpected update behavior Entity state or transaction boundaries are misunderstood Check managed state, merge behavior, and transaction scope.
Slow database access Excessive queries, large result sets, or inefficient fetch plans Inspect SQL, indexes, pagination, and fetch strategies.

23. JPA Best Practices

  • Use descriptive entity and property names.
  • Define primary keys and suitable database constraints.
  • Use Spring Data JPA repositories for common data access operations.
  • Keep business logic in a service layer rather than putting it all in controllers.
  • Use transactions for operations that must be atomic.
  • Prefer DTOs for external API request and response bodies.
  • Validate incoming data before performing persistence operations.
  • Use lazy loading thoughtfully and fetch the data needed by each use case.
  • Use pagination for large collections instead of loading every record.
  • Inspect generated SQL when troubleshooting slow queries.
  • Avoid exposing database entities directly when this creates security or serialization risks.
  • Use database migration tools for controlled production schema changes.
  • Keep database credentials outside source code.
  • Write repository, service, and integration tests.

24. Practical Project: Student Management System

Project Objective: Build a Spring Boot application that manages student records using JPA and a relational database.

Project Requirements

  1. Create a Student entity with ID, name, and email.
  2. Configure Spring Data JPA and a database connection.
  3. Create a StudentRepository extending JpaRepository.
  4. Implement service methods for create, read, update, and delete operations.
  5. Expose REST endpoints using a controller.
  6. Return appropriate HTTP status codes for successful and unsuccessful operations.
  7. Validate incoming student data.
  8. Add exception handling for missing records and invalid requests.
  9. Test endpoints with Postman.
  10. Write automated tests for repository and service behavior.

Expected API Endpoints

HTTP Method Endpoint Purpose
POST /api/students Create a student
GET /api/students Retrieve students
GET /api/students/{id} Retrieve a student by ID
PUT /api/students/{id} Update a student
DELETE /api/students/{id} Delete a student

25. Interview Questions and Answers

Q1. What is JPA?

Answer: JPA is a Java specification that defines standard interfaces and mapping rules for persisting Java objects in relational databases.

Q2. Is JPA an implementation?

Answer: No. JPA is a specification. Hibernate is a popular implementation of that specification.

Q3. What is ORM?

Answer: ORM maps object-oriented classes and properties to relational tables and columns.

Q4. What is an entity?

Answer: An entity is a Java class mapped to persistent data, usually a database table.

Q5. What is the purpose of @Entity?

Answer: It marks a class as a JPA entity.

Q6. What is the purpose of @Id?

Answer: It identifies the primary key of an entity.

Q7. What is EntityManager?

Answer: It manages entity instances, supports persistence operations, and provides query functionality.

Q8. What is a persistence context?

Answer: It tracks managed entity instances and their changes during a unit of work.

Q9. What is the difference between persist() and merge()?

Answer: persist() makes a new entity managed. merge() copies state from a new or detached entity into a managed entity and returns that managed instance.

Q10. What is Spring Data JPA?

Answer: It is a Spring framework project that simplifies JPA data access through repository interfaces, derived queries, and other repository features.

Q11. What is JPQL?

Answer: JPQL is an object-oriented query language that queries entities and their properties rather than directly targeting database tables.

Q12. What is the purpose of @Transactional?

Answer: It defines transaction boundaries so related database operations can be managed as a unit of work.

Q13. What is dirty checking?

Answer: Dirty checking detects changes to managed entities so the persistence provider can synchronize those changes with the database.

Q14. What is the difference between lazy and eager loading?

Answer: Lazy loading defers loading related data until needed, while eager loading requires related data to be fetched eagerly.

Q15. Why should DTOs be used in REST APIs?

Answer: DTOs define the external data contract, help control which fields are exposed, and separate API models from persistence entities.

26. Quick Revision Checklist

  • JPA is a persistence specification, not a standalone ORM implementation.
  • Hibernate is a common JPA implementation.
  • Spring Data JPA simplifies repository-based data access.
  • @Entity maps a Java class to persistent data.
  • @Id defines an entity identifier.
  • @GeneratedValue configures identifier generation.
  • EntityManager manages entity instances and persistence operations.
  • The persistence context tracks managed entities and changes.
  • CRUD operations cover creating, reading, updating, and deleting records.
  • JPQL queries entities and their properties.
  • @Transactional helps manage transaction boundaries.
  • Fetch strategies affect how related data is loaded.
  • Repositories, DTOs, validation, and tests improve application maintainability.

27. Conclusion

The Java Persistence API is a fundamental technology for Java applications that store and retrieve data from relational databases. It provides a standard object-persistence model through entities, identifiers, entity managers, persistence contexts, queries, and transactions.

When combined with Hibernate and Spring Data JPA, developers can implement database access with less repetitive code and a clear separation between controllers, services, and repositories. Understanding entity lifecycle states, transaction management, relationships, query performance, and validation helps build reliable and maintainable enterprise applications.

To continue learning Java and Spring technologies, explore the Advanced Java Training Course, visit the JustAcademy website, or register for a course demo.

Previous Next
whatsapp