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
- Prepare a Spring Boot JPA project
-
Map a Java class to a database table with
@Entity - Spring Data JPA and JpaRepository
- Query methods without writing JPQL
- JPQL
-
@Transactionaland database consistency -
ResponseEntity - What else should you know?
- 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:
- Write the SQL query.
- Execute the query.
- Retrieve the database result.
- 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@ColumnEntityManager- 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 = falsemeans the column should not accept NULL values. -
length = 150specifies 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.
- Hibernate retrieves a book from the database.
- The entity becomes managed by the persistence context.
- We change the book's title.
- Hibernate notices the change.
- 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:
-
Trepresents the entity type. -
IDrepresents the primary key type.
In our example:
JpaRepository<Book, Long>
Means:
-
Bookis our entity. -
Longis 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<Book> findByAuthorAndTitle(
String author,
String title
);
}
Let's understand each method.
1. Find books by author
findByAuthor("Joshua Bloch");
Equivalent query conceptually:
SELECT *
FROM books
WHERE author = 'Joshua Bloch';
2. Ignore case while comparing author
findByAuthorIgnoreCase("joshua bloch");
This performs a case-insensitive comparison according to the query and database semantics.
3. Find books containing a particular word
findByTitleContainingIgnoreCase("java");
This searches for books whose titles contain the word java, ignoring case.
4. Combine multiple conditions
findByAuthorAndTitle(
"Joshua Bloch",
"Effective Java"
);
Conceptually:
SELECT *
FROM books
WHERE author = 'Joshua Bloch'
AND title = 'Effective Java';
Let's understand some commonly used keywords.
-
And: Combines two conditions. -
Or: Combines alternative conditions. -
Between: Checks a range. -
LessThan: Checks whether a value is smaller. -
GreaterThan: Checks whether a value is greater. -
Containing: Searches for a matching substring. -
StartingWith: Matches values beginning with a particular string. -
EndingWith: Matches values ending with a particular string. -
IgnoreCase: Ignores case differences for supported string comparisons. -
IsNull: Checks for NULL values.
Behind the scenes
When Spring Data JPA discovers your repository interface, it analyzes the method names and prepares query implementations.
Repository Interface
|
v
findByAuthorIgnoreCase()
|
v
Parse Method Name
|
v
Identify Entity Property
|
v
Generate Query
|
v
JPQL
|
v
Hibernate
|
v
SQL Query
|
v
Database
This is useful when queries are relatively simple.
But what happens when we need more control?
That's where JPQL becomes useful.
JPQL
JPQL stands for Java Persistence Query Language.
It is a query language defined by Jakarta Persistence.
It allows us to query entities and their properties rather than directly querying database tables and columns.
This is an important difference between JPQL and SQL.
JPQL uses entity and property names
Consider our Java entity:
@Entity
@Table(name = "books")
public class Book {
@Id
private Long id;
private String title;
private String author;
}
Our database table is named:
books
But our entity is named:
Book
Now suppose we want to fetch all books written by Joshua Bloch.
In SQL, we would write:
SELECT *
FROM books
WHERE author = 'Joshua Bloch';
In JPQL, we write:
SELECT b
FROM Book b
WHERE b.author = 'Joshua Bloch';
Notice the difference.
SQL uses:
- Table name:
books - Column name:
author
JPQL uses:
- Entity name:
Book - Java property:
author
Why?
Because JPQL operates on the object model rather than directly on the database schema.
Behind the scenes
JPQL QUERY
|
v
SELECT b FROM Book b
WHERE b.author = ?
|
v
JPA Provider
|
v
Hibernate
|
v
Translate JPQL
|
v
Generate SQL
|
v
Execute Query
|
v
Database
Hibernate translates the JPQL query into SQL suitable for the configured database.
Write custom JPQL with @Query
Spring Data JPA allows us to write custom JPQL queries using the @Query annotation.
For example:
@Query(
"SELECT b FROM Book b WHERE b.author = :author"
)
List<Book> findBooksByAuthor(
@Param("author") String author
);
Let's understand the annotations.
@Query tells Spring Data JPA which query should execute when the repository method is called.
@Param connects the Java method parameter with the named parameter in the JPQL query.
Here:
:author
is the named parameter.
And:
@Param("author") String author
provides its value.
We can also write case-insensitive queries:
@Query("""
SELECT b
FROM Book b
WHERE LOWER(b.author) = LOWER(:author)
""")
List<Book> findBooksByAuthorIgnoreCase(
@Param("author") String author
);
Example:
List<Book> books =
bookRepository.findBooksByAuthorIgnoreCase("joshua bloch");
books.forEach(book ->
System.out.println(book.getTitle())
);
Output:
Effective Java
Why would we use @Query when derived query methods already exist?
Because some queries become difficult to express through method names.
Imagine queries involving:
- Multiple conditions.
- Joins between entities.
- Aggregation.
- Subqueries.
- Complex filtering.
Writing JPQL gives you more control over the query.
JPQL versus native SQL
Sometimes JPQL is not enough.
You might need a database-specific function or a query that takes advantage of a particular database feature.
Spring Data JPA allows native SQL queries through @Query.
Example:
@Query(
value = "SELECT * FROM books WHERE author = :author",
nativeQuery = true
)
List<Book> findBooksUsingNativeSQL(
@Param("author") String author
);
Notice the difference.
JPQL:
SELECT b FROM Book b WHERE b.author = :author
Native SQL:
SELECT * FROM books WHERE author = :author
JPQL works with entities and Java properties.
Native SQL works directly with database tables and columns.
Which one should you choose?
Prefer JPQL when you want database-independent queries based on your entity model.
Use native SQL when you need database-specific SQL features or when a complex SQL query is more appropriate.
Remember that native SQL can make your application more dependent on a particular database.
@Transactional and database consistency
Now let's understand another important annotation.
@Transactional.
You will see this annotation frequently in Spring Boot service classes.
But why do we need it?
Suppose Asha's library application allows users to borrow books.
When a user borrows a book, the application might need to:
- Check whether the book is available.
- Create a borrowing record.
- Update the book's availability.
What happens if the first operation succeeds, the second operation succeeds, but the third operation fails?
The database might end up in an inconsistent state.
We need a way to make sure related database operations succeed or fail together.
This is where transactions come in.
What is a database transaction
A transaction is a group of database operations treated as one logical unit of work.
A transaction follows the well-known ACID properties.
- Atomicity: All operations succeed together or are rolled back together.
- Consistency: A transaction should preserve database rules and constraints.
- Isolation: Concurrent transactions should not interfere with one another beyond the configured isolation guarantees.
- Durability: Once committed, changes should persist according to the database's durability guarantees.
Let's take a simple example.
A user transfers ₹500 from Account A to Account B.
Two operations are needed:
UPDATE accounts
SET balance = balance - 500
WHERE id = 1;
UPDATE accounts
SET balance = balance + 500
WHERE id = 2;
What if the first UPDATE succeeds but the second fails?
We don't want ₹500 to disappear.
Both operations must belong to one transaction.
Conceptually:
BEGIN TRANSACTION
|
v
Deduct ₹500 from A
|
v
Add ₹500 to B
|
v
Both successful?
/ \
Yes No
| |
v v
COMMIT ROLLBACK
| |
v v
Save changes Undo changes
This is the problem @Transactional helps solve in Spring.
Put the transaction boundary in the service layer
Spring provides the @Transactional annotation to define transaction boundaries.
Example:
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class BookService {
private final BookRepository bookRepository;
public BookService(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@Transactional
public void renameBook(Long id, String newTitle) {
Book book = bookRepository
.findById(id)
.orElseThrow();
book.setTitle(newTitle);
}
}
What does @Transactional do here?
It tells Spring that this method should execute within a transaction.
When the method starts, Spring's transaction infrastructure begins or joins an appropriate transaction.
When the method completes successfully, the transaction can commit.
If an applicable exception occurs, the transaction can roll back.
Notice that we didn't call:
bookRepository.save(book);
Why?
Because we loaded the book inside a transaction.
The book is managed by the JPA persistence context.
When we modify its title, Hibernate detects the change through dirty checking and synchronizes it with the database during flush or commit.
Behind the scenes
Controller Calls Service
|
v
Spring Transaction
Begins
|
v
Find Book From Database
|
v
Entity Becomes Managed
|
v
Update Book Object
|
v
Method Completes
|
v
Hibernate Flush
|
v
Commit Transaction
|
v
Database Updated
Why do we usually put @Transactional on service methods?
Because the service layer represents a business operation.
A single business operation might involve multiple repository calls.
We want all those operations to participate in the same transaction.
For example, borrowing a book could involve:
- Updating the book.
- Creating a borrowing record.
- Updating a user's borrowing count.
These operations should belong to one logical unit of work.
Putting the transaction boundary at the service layer makes that intention clear.
Rollback rules and proxy gotchas
Let's understand rollback behaviour.
Consider this example:
@Transactional
public void updateBook(Long id) {
Book book = bookRepository
.findById(id)
.orElseThrow();
book.setTitle("Temporary Title");
throw new IllegalStateException(
"Something went wrong!"
);
}
What happens?
The book's title is changed in memory.
But before the method completes, an exception occurs.
IllegalStateException is an unchecked exception.
By default, Spring rolls back transactions when unchecked exceptions (RuntimeException and its subclasses) or Error escape the transactional method.
The transaction is rolled back.
Expected exception:
java.lang.IllegalStateException: Something went wrong!
After the rollback, the old book title remains in the database.
What about checked exceptions?
By default, checked exceptions do not trigger rollback.
For example, IOException.
When you need a checked exception to trigger rollback, configure it explicitly:
@Transactional(rollbackFor = Exception.class)
public void updateBook(Long id) throws Exception {
// Database operations
throw new Exception("Something failed");
}
There is another interesting behaviour beginners should know.
Self-invocation problem
Spring's default transaction management uses proxies.
A proxy is an object that sits between the caller and the actual service implementation.
When another bean calls a transactional method through the Spring-managed service, the proxy can apply transaction behaviour.
But consider:
@Service
public class BookService {
public void processBook() {
updateBook();
}
@Transactional
public void updateBook() {
// Database operations
}
}
Here, processBook() calls updateBook() directly using this.
The call does not go through the Spring proxy.
Therefore, the transaction annotation on updateBook() is not applied through the default proxy mechanism for this self-invocation.
A better approach is to put the transactional operation in a separate Spring-managed service or call it from another bean through the proxy.
Behind the scenes
Another Spring Bean
|
v
Spring Proxy
|
Apply Transaction
|
v
Actual Service
|
v
Execute Method
But when a method calls another method inside the same object:
Actual Service
|
v
this.updateBook()
|
v
Direct Method Call
|
v
Proxy Is Bypassed
Keep this in mind when debugging transactions that seem to be ignored.
Read only transactions and common behaviour
Not every operation modifies data.
For example, fetching all books is a read operation.
We can mark such methods as read-only:
@Transactional(readOnly = true)
public List<Book> getAllBooks() {
return bookRepository.findAll();
}
Why use readOnly = true?
It communicates that the transaction is intended for reading.
Depending on the persistence provider and database, this can enable useful optimizations.
For example, Hibernate can adjust its flush behaviour to avoid unnecessary dirty checking in suitable read-only transactions.
But remember something important.
readOnly = true is generally a hint for the underlying transaction infrastructure and persistence provider.
It is not a universal security mechanism that guarantees write operations are impossible.
A good default:
- Use
@Transactional(readOnly = true)for read-oriented service methods. - Use
@Transactionalfor methods that modify data. - Put transaction boundaries around complete business operations.
Spring Data JPA also provides transactional behaviour for inherited repository CRUD methods.
However, declared query methods do not automatically receive transaction configuration in every case.
That's another reason why service-level transaction boundaries are useful.
ResponseEntity
Until now, we have focused on database operations.
But how does our backend send the result to the client?
Suppose Ravi sends an HTTP request:
GET /api/books/1
Our application retrieves the book from the database.
Now we need to send the result back.
Should we return a Java object directly?
We can.
But what if we want to control:
- HTTP status code.
- Response headers.
- Response body.
This is where ResponseEntity comes in.
ResponseEntity is a Spring class that represents an entire HTTP response, including its status code, headers, and body.
Build HTTP responses with status and body
Consider a simple REST controller:
@RestController
public class BookController {
@GetMapping("/books")
public String getBooks() {
return "Fetching all books";
}
}
Output:
HTTP/1.1 200 OK
Response body:
Fetching all books
The controller returns a value, and Spring MVC writes it into the HTTP response body.
But what if we want more control?
We can use ResponseEntity.
@GetMapping("/books")
public ResponseEntity<String> getBooks() {
return ResponseEntity.ok("Fetching all books");
}
Output:
HTTP/1.1 200 OK
Response body:
Fetching all books
Let's look at some commonly used methods.
1. Return HTTP 200 OK
return ResponseEntity.ok("Success");
2. Return HTTP 201 Created
return ResponseEntity
.status(HttpStatus.CREATED)
.body("Book created");
3. Return HTTP 404 Not Found
return ResponseEntity.notFound().build();
4. Return HTTP 204 No Content
return ResponseEntity.noContent().build();
5. Return an HTTP response with a custom header
return ResponseEntity
.ok()
.header("X-Application", "Library")
.body("Success");
Why do we need this?
Because HTTP responses contain more than just data.
A good REST API should communicate the correct status of an operation to its clients.
Behind the scenes
Controller Method
|
v
ResponseEntity
|
+--------+--------+
| | |
v v v
Status Headers Body
| | |
+--------+--------+
|
v
Spring MVC Response
|
v
Client
Spring MVC uses HTTP message converters to convert Java response objects into HTTP representations such as JSON.
Create read and not found endpoints
Let's make this more practical.
Suppose our API needs three operations:
- Fetch all books.
- Fetch one book by ID.
- Create a new book.
First, let's create a response DTO.
A DTO is a Data Transfer Object.
We'll discuss it in more detail later.
Create BookResponse.java:
package com.example.library.dto;
public record BookResponse(
Long id,
String title,
String author
) {}
Now create a request DTO:
CreateBookRequest.java
package com.example.library.dto;
public record CreateBookRequest(
String title,
String author
) {}
Now create the service:
BookService.java
package com.example.library.service;
import com.example.library.dto.BookResponse;
import com.example.library.dto.CreateBookRequest;
import com.example.library.entity.Book;
import com.example.library.repository.BookRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class BookService {
private final BookRepository bookRepository;
public BookService(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@Transactional(readOnly = true)
public List<BookResponse> getAllBooks() {
return bookRepository.findAll()
.stream()
.map(this::toResponse)
.toList();
}
@Transactional(readOnly = true)
public Optional<BookResponse> getBookById(Long id) {
return bookRepository.findById(id)
.map(this::toResponse);
}
@Transactional
public BookResponse createBook(CreateBookRequest request) {
Book book = new Book(
request.title(),
request.author()
);
Book savedBook = bookRepository.save(book);
return toResponse(savedBook);
}
private BookResponse toResponse(Book book) {
return new BookResponse(
book.getId(),
book.getTitle(),
book.getAuthor()
);
}
}
Notice that the service does not know anything about HTTP status codes.
Its responsibility is to handle business operations.
Now let's create our controller.
BookController.java
package com.example.library.controller;
import com.example.library.dto.BookResponse;
import com.example.library.dto.CreateBookRequest;
import com.example.library.service.BookService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService bookService;
public BookController(BookService bookService) {
this.bookService = bookService;
}
// Fetch all books
@GetMapping
public ResponseEntity<List<BookResponse>> getAllBooks() {
return ResponseEntity.ok(
bookService.getAllBooks()
);
}
// Fetch book by ID
@GetMapping("/{id}")
public ResponseEntity<BookResponse> getBookById(
@PathVariable Long id
) {
Optional<BookResponse> book =
bookService.getBookById(id);
if (book.isEmpty()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(book.get());
}
// Create a new book
@PostMapping
public ResponseEntity<BookResponse> createBook(
@RequestBody CreateBookRequest request
) {
BookResponse savedBook =
bookService.createBook(request);
return ResponseEntity
.status(HttpStatus.CREATED)
.body(savedBook);
}
}
Let's understand the important annotations:
-
@RestController: Marks the class as a REST controller. -
@RequestMapping: Defines the common URL prefix. -
@GetMapping: Handles HTTP GET requests. -
@PostMapping: Handles HTTP POST requests. -
@PathVariable: Extracts values from the URL. -
@RequestBody: Converts the incoming JSON request body into a Java object.
The important part is the return type:
ResponseEntity<BookResponse>
This means our controller returns an HTTP response with a BookResponse body.
Put together a REST request flow
Let's prepare some initial data.
Update your main application class:
LibraryApplication.java
package com.example.library;
import com.example.library.entity.Book;
import com.example.library.repository.BookRepository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import java.util.List;
@SpringBootApplication
public class LibraryApplication {
public static void main(String[] args) {
SpringApplication.run(
LibraryApplication.class,
args
);
}
@Bean
CommandLineRunner loadData(BookRepository repository) {
return args -> {
if (repository.count() == 0) {
repository.saveAll(
List.of(
new Book(
"Effective Java",
"Joshua Bloch"
),
new Book(
"Clean Code",
"Robert C. Martin"
)
)
);
}
};
}
}
Our package structure now looks like this:
com.example.library
|
+-- LibraryApplication.java
|
+-- controller
| +-- BookController.java
|
+-- service
| +-- BookService.java
|
+-- repository
| +-- BookRepository.java
|
+-- entity
| +-- Book.java
|
+-- dto
+-- BookResponse.java
+-- CreateBookRequest.java
Now start the application.
Let's send some requests.
1. Fetch all books
Request:
curl -i http://localhost:8080/api/books
Expected response:
HTTP/1.1 200
Content-Type: application/json
Response body:
[
{
"id": 1,
"title": "Effective Java",
"author": "Joshua Bloch"
},
{
"id": 2,
"title": "Clean Code",
"author": "Robert C. Martin"
}
]
2. Fetch a book by ID
Request:
curl -i http://localhost:8080/api/books/1
Expected response:
HTTP/1.1 200
Content-Type: application/json
Response body:
{
"id": 1,
"title": "Effective Java",
"author": "Joshua Bloch"
}
3. Fetch a book that doesn't exist
Request:
curl -i http://localhost:8080/api/books/999
Expected response:
HTTP/1.1 404
There is no response body.
Why?
Because our controller explicitly returns:
ResponseEntity.notFound().build();
4. Create a new book
Request:
curl -i -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"Head First Java","author":"Kathy Sierra"}'
Expected response:
HTTP/1.1 201
Content-Type: application/json
Response body:
{
"id": 3,
"title": "Head First Java",
"author": "Kathy Sierra"
}
We returned HTTP 201 because a new resource was created.
Notice how all the concepts we learned are working together.
Complete request flow
CLIENT
|
v
HTTP Request (JSON)
|
v
CONTROLLER
|
v
SERVICE
|
@Transactional
|
v
REPOSITORY
|
v
JpaRepository
|
v
Hibernate
|
v
JDBC
|
v
DATABASE
|
v
Query / Result
|
v
SERVICE
|
v
BookResponse
|
v
ResponseEntity
|
v
CLIENT
This is a typical Spring Boot backend request lifecycle.
What else should you know?
We have covered the main topics, but there are a few related concepts that are important when building real-world applications.
Entity versus DTO
One thing you'll notice in our application is that we don't directly return the Book entity from the controller.
Instead, we return:
BookResponse
Why?
Because an Entity and a DTO serve different purposes.
Entity
An entity represents persistent data.
It is mapped to a database table.
Example:
@Entity
public class Book {
@Id
private Long id;
private String title;
private String author;
}
DTO
A DTO is used to transfer data between application boundaries.
Example:
public record BookResponse(
Long id,
String title
) {}
Notice that the DTO doesn't contain the author field.
Maybe our API should expose only the ID and title.
Using a DTO gives us control over what data is returned.
Why should we avoid directly returning entities?
- It prevents unnecessary exposure of database fields.
- It separates the API structure from the database structure.
- It helps avoid JSON serialization problems with entity relationships.
- It makes API changes easier.
A simple rule:
Use entities for persistence and DTOs for API communication.
Lazy loading and open in view
Consider a different application with two entities:
- Department
- Employee
One department can have many employees.
We might define a relationship like this:
@OneToMany(mappedBy = "department")
private List<Employee> employees;
Now imagine fetching one department.
Should Hibernate immediately retrieve every employee belonging to it?
Not necessarily.
This is where Lazy Loading comes in.
Lazy loading means related data is loaded only when it is accessed, provided the mapping uses lazy fetching and the persistence context is still available.
For example:
Department department =
departmentRepository.findById(1L).orElseThrow();
// Access employees later
List<Employee> employees = department.getEmployees();
The employee collection might be loaded only when the application accesses it.
This can save unnecessary database queries.
However, if the persistence context is already closed when we access the lazy relationship, Hibernate may throw:
org.hibernate.LazyInitializationException:
could not initialize proxy - no Session
Another problem is the N+1 query problem.
For example, you fetch 10 departments using one query.
Then, while iterating over them, you access the employees of each department.
Hibernate might execute another query for each department.
Instead of one query, you end up executing 11 queries.
That's why we need to understand:
- Lazy loading.
- Eager loading.
- Fetch joins.
- Entity graphs.
- DTO projections.
Also, in our application, we configured:
spring.jpa.open-in-view=false
This prevents Spring Boot's Open EntityManager in View mechanism from keeping the JPA EntityManager open across the whole web request.
It encourages fetching the data required by the API within the service-layer transaction.
Pagination and sorting
Imagine our library application has 100,000 books.
Should we fetch all 100,000 records whenever the client requests /api/books?
Definitely not.
We need pagination.
Pagination means dividing a large result set into smaller pages.
Spring Data JPA supports pagination through Pageable.
Example:
Pageable pageable = PageRequest.of(0, 10);
Page<Book> books = bookRepository.findAll(pageable);
What do these values mean?
PageRequest.of(0, 10)
-
0: First page. -
10: Number of records per page.
The result is a Page<Book>.
It gives us access to:
- Page content.
- Total number of elements.
- Total number of pages.
- Current page number.
- Whether another page exists.
We can also add sorting:
Pageable pageable = PageRequest.of(
0,
10,
Sort.by("title").ascending()
);
Page<Book> books = bookRepository.findAll(pageable);
This retrieves the first 10 books sorted by title.
Why does this matter?
Because fetching only the records required by the client improves efficiency and reduces unnecessary database work.
Which one should I use?
Now let's summarize when to use each technology.
JDBC
Choose JDBC when:
- You want low-level database control.
- You want to write SQL manually.
- You need to understand database connectivity.
JdbcTemplate
Choose JdbcTemplate when:
- You want to write custom SQL.
- You want Spring to manage JDBC boilerplate.
- You want more direct control over SQL execution.
Spring Data JPA
Choose Spring Data JPA when:
- Your application works primarily with Java entities.
- You need common CRUD operations.
- You want repository interfaces.
- You want automatic query generation.
JpaRepository
Choose JpaRepository when:
- Your repository needs standard CRUD operations.
- You need pagination and sorting.
- You want JPA-specific repository functionality.
JPQL
Choose JPQL when:
- You need custom queries based on entity properties.
- Derived query methods become difficult to read.
- You want object-oriented queries instead of direct database SQL.
Native SQL
Choose native SQL when:
- You need database-specific features.
- Your query is easier to express in SQL.
- You need direct access to database-specific functionality.
@Transactional
Use it when:
- Multiple database operations belong to one business operation.
- You need atomic database operations.
- You need predictable transaction boundaries.
ResponseEntity
Use it when:
- You need to control HTTP status codes.
- You need to add response headers.
- You need different response formats based on the operation result.
My recommendation:
For most typical Spring Boot backend applications, start with:
- Spring Data JPA for persistence.
- JpaRepository for common CRUD operations.
- JPQL for custom entity-based queries.
-
@Transactionalat service boundaries. - DTOs for API request and response objects.
- ResponseEntity when controlling HTTP responses.
However, don't assume JPA is always better than JDBC.
For complex reporting, bulk operations, or database-specific queries, JdbcTemplate or native SQL can be a better fit.
Common mistakes
Let's look at six mistakes beginners frequently make.
1. Thinking JPA and Hibernate are the same thing
JPA is a persistence specification, while Hibernate is an implementation of that specification.
Understand the difference before working with JPA annotations.
2. Confusing JpaRepository generic parameters
The first parameter is the entity type, and the second is the primary key type.
For example:
JpaRepository<Book, Long>
Make sure the second type matches your entity's ID field.
3. Writing SQL table names inside JPQL queries
JPQL works with entity names and Java properties, not directly with database table and column names.
Use Book and author in JPQL, not books and author as table/column references.
4. Assuming save() always executes SQL immediately
JPA manages persistence operations through its persistence context.
Changes may be synchronized during flush or transaction commit.
Understand dirty checking and the entity lifecycle.
5. Putting @Transactional on a method called only through self-invocation
Spring's default proxy-based transaction management intercepts external calls through the proxy.
A direct method call inside the same class bypasses that proxy.
Move transactional work into another Spring-managed bean when appropriate.
6. Returning JPA entities directly from every REST controller
Entities represent database persistence structures, while DTOs represent API data.
Use DTOs to control what your API exposes and avoid serialization issues involving entity relationships.
Quick recap
Let's revise everything we learned.
- ORM maps Java objects to relational database tables.
- JPA, now Jakarta Persistence, is a persistence specification.
- Hibernate is a popular JPA implementation.
- Spring Data JPA simplifies repository development.
-
@Entitymarks a Java class as a persistent entity. -
@Iddefines the primary key. -
@GeneratedValueconfigures primary key generation. - The persistence context manages entity instances.
- Dirty checking automatically detects changes to managed entities.
-
JpaRepository<T, ID>provides common persistence operations. - Spring Data JPA generates repository implementations automatically.
- Derived query methods generate queries from method names.
- JPQL queries entities and Java properties instead of database tables and columns.
-
@Queryallows us to define custom JPQL or native SQL queries. -
@Transactionaldefines transaction boundaries. - Unchecked exceptions and errors trigger rollback by default.
-
readOnly = trueprovides a read-only transaction hint and optimization opportunity. - Spring's default proxy-based transaction mechanism does not intercept self-invocation.
-
ResponseEntitycontrols HTTP status codes, headers, and response bodies. - DTOs separate API data from database entities.
- Pagination helps retrieve large datasets efficiently.
Try it yourself
Practice idea:
Extend the Library Management application.
Implement the following operations:
- Fetch all books.
- Fetch a book by ID.
- Add a new book.
- Update a book's title.
- Delete a book.
- Find books by author.
- Find books containing a particular keyword.
- Fetch books using pagination and sorting.
Use the following structure:
Controller
|
v
Service
|
v
Repository
|
v
Database
Use JpaRepository for CRUD operations, derived queries for simple searches, and JPQL for custom queries.
Use ResponseEntity to return appropriate HTTP status codes.
Bonus experiment:
Build the same Library Management application twice.
First, use JdbcTemplate.
Then, replace the persistence layer with Spring Data JPA.
Compare:
- Amount of code.
- SQL query handling.
- Object mapping.
- CRUD operations.
- Transaction management.
Try to understand what Spring Data JPA and Hibernate are doing for you behind the scenes.
If this helped, or if you spotted something I should fix, tell me in the comments. I'm still learning too.
Top comments (0)