In Part 1, we learned how Spring manages objects using @Component, @Service, and @Repository.

In Part 2, we learned how Java communicates with databases using JDBC and how Spring simplifies database operations using JdbcTemplate.

But there is another question.

Do we really need to write SQL queries for every database operation?

Imagine Asha is building a library management application.

She wants to perform operations like:

  • Save a new book.
  • Find a book by its ID.
  • Fetch all books.
  • Update book information.
  • Delete a book.

With JDBC, we write SQL queries and map the returned rows into Java objects.

It works perfectly, but writing SQL and mapping database records manually for every operation can become repetitive.

Wouldn't it be nice if we could work directly with Java objects instead?

That's exactly what technologies like JPA and Hibernate help us achieve.

But there are several terms that beginners often confuse:

  • JPA
  • Hibernate
  • Spring Data JPA
  • JpaRepository
  • JPQL
  • @Transactional
  • ResponseEntity

They are related, but they are not the same thing.

In this post, we'll understand each concept from the ground up and build a small Spring Boot REST API using Spring Data JPA.

Versions used in this post:

  • Java 17
  • Spring Boot 4.2.0
  • Spring Framework 7.1.0
  • Spring Data JPA 4.2.0
  • Jakarta Persistence 3.2.0

The examples use Java 17-compatible syntax.

Table of contents

  • First understand what JPA actually is
    • JDBC versus ORM
    • JPA is a specification not an implementation
    • What Hibernate does behind the scenes
  • Prepare a Spring Boot JPA project
    • Add dependencies
    • Configure H2 and Hibernate
  • Map a Java class to a database table with @Entity
    • Create the Book entity
    • Understand primary key generation
    • What is the persistence context
  • Spring Data JPA and JpaRepository
    • What do the JpaRepository type parameters mean
    • Which methods do we get for free
    • What happens when we call save
  • Query methods without writing JPQL
    • Derive queries from method names
  • JPQL
    • JPQL uses entity and property names
    • Write custom JPQL with @Query
    • JPQL versus native SQL
  • @Transactional and database consistency
    • What is a database transaction
    • Put the transaction boundary in the service layer
    • Rollback rules and proxy gotchas
    • Read only transactions and common behaviour
  • ResponseEntity
    • Build HTTP responses with status and body
    • Create read and not found endpoints
    • Put together a REST request flow
  • What else should you know?
    • Entity versus DTO
    • Lazy loading and open in view
    • Pagination and sorting
  • Which one should I use?
  • Common mistakes
  • Quick recap
  • Try it yourself

First understand what JPA actually is

Before jumping into annotations and repository interfaces, let's understand why JPA exists.

JDBC versus ORM

In Part 2, we learned how JDBC works.

Suppose we want to retrieve a book from a database.

Using JDBC, we write something like this:

String sql = "SELECT * FROM books WHERE id = ?"; Book book = jdbcTemplate.queryForObject( sql, (rs, rowNum) -> new Book( rs.getLong("id"), rs.getString("title"), rs.getString("author") ), 1L ); 

We need to:

  1. Write the SQL query.
  2. Execute the query.
  3. Retrieve the database result.
  4. Convert the result into a Java object.

Notice the last step.

The database returns rows, but our application works with Java objects.

We manually convert one representation into another.

Now imagine doing this for hundreds of tables and thousands of queries.

It becomes repetitive.

This is where ORM comes in.

ORM stands for Object Relational Mapping.

It is a technique that maps Java objects to relational database tables.

For example:

Our Java class:

public class Book { private Long id; private String title; private String author; } 

Our database table:

+----+----------------+------------------+ | id | title | author | +----+----------------+------------------+ | 1 | Effective Java | Joshua Bloch | | 2 | Clean Code | Robert C. Martin | +----+----------------+------------------+ 

ORM connects these two representations.

Conceptually:

 JAVA APPLICATION | v Java Objects | v ORM Mapping Layer | +-----+-----+ | | v v Database Java Object Tables Mapping | | +-----+-----+ | v Database 

Instead of manually converting every database row into a Java object, an ORM framework can handle much of this work.

Why do we need ORM?

Because object-oriented applications and relational databases represent data differently.

ORM provides a bridge between these two worlds.

However, ORM doesn't eliminate SQL.

It generates SQL behind the scenes, and developers still need to understand database queries, indexes, joins, and performance.

JPA is a specification not an implementation

Now let's understand JPA.

JPA stands for Java Persistence API.

Today, its official name is Jakarta Persistence because the technology moved from the Java EE namespace to Jakarta EE.

JPA is a specification that defines how Java applications should manage persistence and map Java objects to relational databases.

Wait, what does specification mean?

Think about an interface in Java.

An interface defines what operations should be available, but it doesn't necessarily provide the actual implementation.

For example:

public interface PaymentService { void makePayment(); } 

Any class implementing this interface must provide the makePayment() method.

The interface defines the contract.

Similarly, JPA defines a standard contract for persistence-related functionality.

It specifies things such as:

  • How entities are defined.
  • How objects are mapped to database tables.
  • How entities are persisted.
  • How database queries are performed.
  • How transactions interact with persistence.

Some important JPA APIs and annotations include:

  • @Entity
  • @Id
  • @GeneratedValue
  • @Column
  • EntityManager
  • JPQL

But JPA itself is not the engine that executes database operations.

We need an implementation.

What Hibernate does behind the scenes

Hibernate is one of the most popular implementations of the JPA specification.

Remember the difference:

  • JPA defines the standard.
  • Hibernate implements that standard.

Let's understand this with an analogy.

Think of JPA as an interface:

public interface PersistenceProvider { void save(Object object); Object find(Object id); } 

And Hibernate as an implementation:

public class HibernateProvider implements PersistenceProvider { @Override public void save(Object object) { // Actual persistence logic } @Override public Object find(Object id) { // Actual database retrieval logic return null; } } 

This is only a conceptual example, not actual JPA source code.

The idea is that JPA defines the contract, and Hibernate provides the implementation.

But where does Spring Data JPA fit into this?

We have one more layer.

Spring Data JPA simplifies the way we write database access code.

It provides repository abstractions and automatically creates repository implementations.

Let's put everything together.

 YOUR APPLICATION | v Spring Data JPA | v JPA STANDARD (Jakarta API) | v Hibernate (Implementation) | v JDBC | v JDBC DRIVER | v DATABASE 

Each technology has a different responsibility.

  • Spring Data JPA: Simplifies repository development.
  • JPA: Defines the persistence standard.
  • Hibernate: Implements the JPA standard.
  • JDBC: Provides database connectivity.
  • JDBC Driver: Communicates with the actual database.

This distinction is extremely important.

Spring Data JPA is not Hibernate, and Hibernate is not JPA.

Prepare a Spring Boot JPA project

Now that we understand the concepts, let's prepare our project.

We'll continue with our Library Management application.

We will use:

  • Spring Boot
  • Spring Data JPA
  • Hibernate
  • H2 Database
  • Spring MVC

Add dependencies

Add the following dependencies to your pom.xml:

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>4.2.0</version> <relativePath/> </parent> <properties> <java.version>17</java.version> </properties> <dependencies> <!-- Spring Data JPA and Hibernate --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- Spring MVC and REST API support --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webmvc</artifactId> </dependency> <!-- H2 Database --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies> 

Notice that we haven't specified versions for individual dependencies.

Spring Boot's dependency management selects compatible versions.

Also, Spring Boot 4.2 introduces the dedicated spring-boot-starter-webmvc starter. Older projects commonly use spring-boot-starter-web, which is deprecated in favour of the newer starter in this generation.

What do these dependencies provide?

spring-boot-starter-data-jpa provides:

  • Spring Data JPA.
  • Hibernate as the default JPA implementation.
  • Spring ORM integration.
  • Required persistence infrastructure.

spring-boot-starter-webmvc provides:

  • Spring MVC.
  • REST controller support.
  • Embedded Tomcat.
  • HTTP request and response handling.

h2 provides our database.

Configure H2 and Hibernate

Create or update:

src/main/resources/application.properties

spring.datasource.url=jdbc:h2:mem:librarydb;DB_CLOSE_DELAY=-1 spring.datasource.username=sa spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.show-sql=true spring.jpa.open-in-view=false 

Let's understand the important properties.

1. Database configuration

spring.datasource.url=jdbc:h2:mem:librarydb;DB_CLOSE_DELAY=-1 

This connects our application to an in-memory H2 database.

2. Hibernate DDL configuration

spring.jpa.hibernate.ddl-auto=create-drop 

This tells Hibernate to create the required database tables when the application starts and drop them when the application shuts down.

We'll understand this better when we create our entity.

Other possible values include:

  • none: Do not manage the schema.
  • validate: Check whether the schema matches the entity mappings.
  • update: Attempt to update the schema.
  • create: Create the schema when starting.
  • create-drop: Create on startup and drop on shutdown.

For learning, create-drop is convenient.

For production databases, don't rely on Hibernate's automatic schema update as your migration strategy. Prefer tools such as Flyway or Liquibase.

3. Show SQL

spring.jpa.show-sql=true 

This displays SQL generated by Hibernate in the application logs.

It helps us understand what is happening behind the scenes.

4. Disable Open EntityManager in View

spring.jpa.open-in-view=false 

We'll discuss this property later.

For now, it helps keep our database access inside the service-layer transaction instead of allowing lazy database access to continue into the web response processing stage.

Behind the scenes

When Spring Boot starts:

 Spring Boot Startup | v Read application.properties | v Create DataSource | v Initialize Hibernate | v Create EntityManagerFactory | v Initialize JPA Repositories | v Application Ready 

Now let's create our first entity.

Map a Java class to a database table with @Entity

This is where JPA becomes interesting.

Remember our Book Java class?

We want Hibernate to understand that this class represents a database table.

How do we tell it?

Using the @Entity annotation.

@Entity tells the JPA provider that a Java class represents a persistent entity.

An entity is an object whose state can be stored and retrieved from a database.

Create the Book entity

Create a package named:

com.example.library.entity

Inside it, create Book.java.

package com.example.library.entity; import jakarta.persistence.Entity; import jakarta.persistence.Table; import jakarta.persistence.Id; import jakarta.persistence.Column; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; @Entity @Table(name = "books") public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, length = 150) private String title; @Column(nullable = false, length = 120) private String author; // Required by JPA protected Book() { } public Book(String title, String author) { this.title = title; this.author = author; } public Long getId() { return id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } } 

Let's understand the annotations one by one.

1. @Entity

@Entity public class Book { } 

Marks the class as an entity.

Hibernate recognizes it and manages its persistence.

2. @Table

@Table(name = "books") 

Specifies the database table name.

Our Java class is named Book, but we want the table name to be books.

That's why we use @Table.

3. @Id

@Id private Long id; 

Every entity must have a primary key.

A primary key uniquely identifies an entity record.

Here, the id field is our primary key.

4. @Column

@Column(nullable = false, length = 150) private String title; 

Specifies mapping details for the database column.

Here:

  • nullable = false means the column should not accept NULL values.
  • length = 150 specifies the column's length.

5. No-argument constructor

protected Book() { } 

JPA requires an accessible public or protected no-argument constructor for entity instantiation.

That is why we included it.

Also, a JPA entity should not be a Java record or a final class under the Jakarta Persistence entity-class rules.

Behind the scenes

When Hibernate discovers our Book entity, it understands the mapping:

 JAVA CLASS | v @Entity | v Book.java | +---------+---------+ | | | v v v id title author | | | v v v PRIMARY KEY COLUMN COLUMN | | | +---------+---------+ | v BOOKS TABLE 

The entity mapping provides the information Hibernate needs to work with the database table.

Understand primary key generation

You might have noticed this annotation:

@GeneratedValue(strategy = GenerationType.IDENTITY) 

Why do we need it?

Imagine inserting a book.

Without automatic ID generation, we would have to assign a unique ID manually every time.

For example:

Book book = new Book("Effective Java", "Joshua Bloch"); 

Where does the ID come from?

GenerationType.IDENTITY tells the persistence provider to use a database identity column for generating primary keys.

In our H2 database, the database generates the ID automatically.

Other generation strategies include:

  • IDENTITY: Uses a database identity column.
  • SEQUENCE: Uses a database sequence.
  • TABLE: Uses a database table to manage generated identifiers.
  • AUTO: Lets the persistence provider choose an appropriate strategy.

For this example, we'll use IDENTITY.

What is the persistence context

Now let's understand one of the most important JPA concepts.

Suppose we retrieve a book from the database:

Book book = repository.findById(1L).orElseThrow(); 

Now imagine updating its title:

book.setTitle("Updated Effective Java"); 

Wait!

We didn't execute an UPDATE query.

We didn't call jdbcTemplate.update().

We didn't even call repository.save().

So how does the database know that the title changed?

This is where the Persistence Context comes in.

A persistence context is an environment that manages entity instances and tracks their changes.

For a given entity identity, the persistence context maintains a unique managed entity instance.

Think of it as a tracking area for Java objects that are currently managed by JPA.

Behind the scenes

 Persistence Context | +------+------+ | | v v Book 1 Book 2 | | v v ID = 1 ID = 2 Title Title | | +------+------+ | v Change Tracking | v Database Sync 

Let's understand what happens.

  1. Hibernate retrieves a book from the database.
  2. The entity becomes managed by the persistence context.
  3. We change the book's title.
  4. Hibernate notices the change.
  5. At flush or transaction commit, Hibernate synchronizes the changes with the database.

This automatic change detection is called Dirty Checking.

Let's see a practical example:

@Transactional public void renameBook(Long id) { Book book = repository.findById(id).orElseThrow(); book.setTitle("Updated Effective Java"); } 

The entity is managed inside the transaction.

When the transaction commits, Hibernate detects the changed field and generates an UPDATE statement.

Expected SQL (illustrative):

UPDATE books SET title = ? WHERE id = ?; 

Output after retrieving the book again:

Updated Effective Java 

This is one of the major advantages of JPA.

We can work with Java objects, and Hibernate handles the synchronization with the database.

Spring Data JPA and JpaRepository

Now we understand JPA and Hibernate.

But there is still one problem.

Do we need to write EntityManager code for every database operation?

Not necessarily.

Spring Data JPA makes this much easier.

It provides repository interfaces that allow us to perform common database operations without manually writing their implementations.

This is where JpaRepository comes in.

What do the JpaRepository type parameters mean

You might have seen code like this:

public interface BookRepository extends JpaRepository<Book, Long> { } 

What exactly does JpaRepository<Book, Long> mean?

JpaRepository is a generic interface.

It accepts two important type parameters:

JpaRepository<T, ID> 

Where:

  • T represents the entity type.
  • ID represents the primary key type.

In our example:

JpaRepository<Book, Long> 

Means:

  • Book is our entity.
  • Long is the type of its primary key.

Why Long?

Because our entity contains:

private Long id; 

If our entity had an Integer ID, we would use:

JpaRepository<Book, Integer> 

If it had a String ID:

JpaRepository<Book, String> 

The second generic parameter must match the entity's identifier type.

Which methods do we get for free

This is the interesting part.

Consider our repository interface:

package com.example.library.repository; import com.example.library.entity.Book; import org.springframework.data.jpa.repository.JpaRepository; public interface BookRepository extends JpaRepository<Book, Long> { } 

We haven't implemented a single method.

We haven't written SQL queries.

We haven't used EntityManager.

Yet we can perform several database operations.

For example:

1. Save a book

Book book = new Book( "Effective Java", "Joshua Bloch" ); bookRepository.save(book); 

2. Find a book by ID

Optional<Book> book = bookRepository.findById(1L); 

3. Fetch all books

List<Book> books = bookRepository.findAll(); 

4. Delete a book

bookRepository.deleteById(1L); 

5. Count books

long count = bookRepository.count(); 

6. Check whether a book exists

boolean exists = bookRepository.existsById(1L); 

Some commonly used inherited operations are:

  • save()
  • saveAll()
  • findById()
  • findAll()
  • existsById()
  • count()
  • deleteById()
  • delete()
  • flush()

We get these operations through the repository abstraction.

How does this work when we haven't implemented anything?

Spring Data JPA creates the repository implementation automatically at runtime.

A commonly used implementation is SimpleJpaRepository.

Conceptually:

 BookRepository Interface | v Spring Data JPA | v Repository Proxy Created | v SimpleJpaRepository | v EntityManager | v Hibernate | v Database 

When we inject BookRepository, Spring provides the generated repository implementation.

That's why we don't need to write the implementation ourselves.

One important point:

BookRepository does not need @Repository explicitly.

Spring Data JPA detects repository interfaces and registers their implementations automatically.

What happens when we call save

Let's understand what actually happens when we execute:

Book book = new Book( "Clean Code", "Robert C. Martin" ); Book savedBook = bookRepository.save(book); 

Does save() directly execute an SQL INSERT?

Not necessarily at the exact moment you call it.

Spring Data JPA delegates the operation to its repository implementation.

Depending on whether the entity is considered new or existing, it typically calls either:

  • EntityManager.persist()
  • EntityManager.merge()

For a newly created book with a null ID, Spring Data JPA normally treats it as a new entity and uses persist().

For an existing detached entity, it can use merge().

Behind the scenes

 bookRepository.save(book) | v SimpleJpaRepository | v Is the entity new? | +-----+-----+ | | Yes No | | v v persist() merge() | | +-----+-----+ | v Persistence Context | v Hibernate | v Generate SQL | v Database 

For new entities, Hibernate may execute the INSERT during save() or later during flush/transaction commit, depending on the identifier strategy and execution context.

The important thing is that calling save() does not mean SQL must always be executed immediately.

Also, always use the returned entity:

Book savedBook = bookRepository.save(book); 

This matters particularly when JPA uses merge(), because the returned instance is the managed instance.

Query methods without writing JPQL

So far, we have used methods that Spring Data JPA provides automatically.

But what if we want to find books based on their author?

For example:

  • Find books by author.
  • Find books by title.
  • Find books containing a particular word.
  • Find books written after a particular date.

Do we need to write queries for every operation?

Not always.

Spring Data JPA supports Derived Query Methods.

Derive queries from method names

A derived query is a database query that Spring Data JPA generates by analyzing the repository method name.

For example:

List<Book> findByAuthor(String author); 

What does this method name tell Spring?

  • find: We want to retrieve records.
  • By: We are specifying a condition.
  • Author: The condition is based on the entity's author property.

Spring Data JPA understands the method name and generates the corresponding query.

Let's add a few methods to our repository:

public interface BookRepository extends JpaRepository<Book, Long> { List<Book> findByAuthor(String author); List<Book> findByAuthorIgnoreCase(String author); List<Book> findByTitleContainingIgnoreCase(String keyword); List<BookSource:https://dev.to/mayur_bodhare/spring-data-jpa-explained-jparepository-jpql-transactions-and-responseentity-a0g

Related posts