JPA Custom Queries
@Query with JPQL and native SQL, named parameters, @Modifying, projections
- Write JPQL queries with @Query annotation
- Execute UPDATE and DELETE with @Modifying
- Use interface-based projections to fetch partial data
@Repository interface that extends JpaRepository, using save() and findById(), and the concept of a JPA EntityManager and Persistence Context. If not, review those topics first.Overview
Spring Data JPA provides several built-in CRUD methods (save(), findById(), deleteById(), etc.) through JpaRepository. However, real-world applications almost always require custom queries — filtering by specific fields, joining tables, paginating results, and more.
JPA provides multiple mechanisms to write custom queries, each suited to different levels of complexity:
| Mechanism | Best For | Writes SQL/JPQL? |
|---|---|---|
| Derived Query | Simple filters, reads, deletes | No — auto-generated from method name |
JPQL (@Query) | Complex filters, joins, projections | Yes — JPQL (object-based) |
@NamedQuery | Reusable queries across codebase | Yes — JPQL |
@Modifying | Update/Delete via JPQL | Yes — JPQL |
| Native Query | Raw SQL, DB-specific features | Yes — SQL |
This guide covers all of the above in depth.
Part 1 Derived Queries
Overview
A Derived Query (also called a query method) is a Spring Data JPA feature where the query is automatically generated by parsing the method name you write in your repository interface. You write no SQL or JPQL — JPA reads your method name and converts it into a query.
Why This Concept Exists
Writing a JPQL or SQL query for every simple filter (find by name, find by email, delete by status) is repetitive and verbose. Derived queries let you express simple queries purely through a method name following a strict naming convention, eliminating boilerplate.
Definition
A Derived Query is a repository method whose query is automatically generated by Spring Data JPA at startup time by parsing the method name according to a defined naming convention. No@Queryannotation is required.
How JPA Parses Method Names (Internal Working)
Internally, Spring Data JPA uses a regex pattern (defined in a class called Part) to parse your method name into a structured query. The method name must match this regex, otherwise Spring will fail at application startup with an error.
The recognized prefixes (what your method name must start with) are:
1find, read, get, query, search, stream, count, exists, delete, removeAfter the prefix, the structure is:
1<prefix><OptionalDescription>By<FieldName><Keyword><FieldName>...- Everything between the prefix and
Byis ignored by JPA (it is just for readability). - Everything after
Bymust correspond to entity field names (in camelCase). - Keywords like
And,Or,Between,IsNull,Like,In,GreaterThan, etc., can follow field names.
Naming Convention Structure
1findUserDetailsByNameAndPhone2│ │ │ │ │ │3│ │ │ │ │ └─ second field name (entity field)4│ │ │ │ └─── keyword: And5│ │ │ └──────── first field name: name (entity field)6│ │ └────────── keyword: By (starts the WHERE clause)7│ └───────────────────── optional description (ignored by JPA)8└────────────────────────── prefix: find → SELECTSupported Prefixes and Their SQL Equivalents
| Prefix | Generated SQL Type |
|---|---|
find, read, get, query, search, stream | SELECT |
count | SELECT COUNT(*) |
exists | SELECT CASE WHEN COUNT(*) > 0 THEN true ELSE false END |
delete, remove | DELETE |
Supported Keywords (Comparisons and Conditions)
These keywords can be appended after a field name in the method name:
| Keyword in Method | SQL Equivalent | Example Method |
|---|---|---|
And | AND | findByNameAndPhone |
Or | OR | findByNameOrUserId |
Between / IsBetween | BETWEEN ? AND ? | findByAgeBetween |
LessThan | < | findByAgeLessThan |
LessThanEqual | <= | findByAgeLessThanEqual |
GreaterThan | > | findByAgeGreaterThan |
GreaterThanEqual | >= | findByAgeGreaterThanEqual |
IsNull / Null | IS NULL | findByPhoneIsNull |
IsNotNull / NotNull | IS NOT NULL | findByPhoneIsNotNull |
Like | LIKE ? | findByNameLike |
NotLike | NOT LIKE ? | findByNameNotLike |
StartingWith | LIKE ?% | findByNameStartingWith |
EndingWith | LIKE %? | findByNameEndingWith |
Containing | LIKE %?% | findByNameContaining |
In | IN (?) | findByNameIn |
NotIn | NOT IN (?) | findByNameNotIn |
True | = true | findByActiveTrue |
False | = false | findByActiveFalse |
OrderBy | ORDER BY | findByNameOrderByAgeDesc |
Supported Operations
SELECT) and delete (DELETE) operations. For insert and update, use the built-in save() method or @Modifying + @Query (covered later).
This is because save() already handles both insert and update (upsert behavior based on whether the entity has an ID).Syntax
1// In your repository interface2public interface UserDetailRepository extends JpaRepository<UserEntity, Long> {3
4 // SELECT * FROM user_detail WHERE name = ?5 List<UserEntity> findUserDetailsByName(String name);6
7 // SELECT * FROM user_detail WHERE name = ? AND phone = ?8 List<UserEntity> findUserDetailsByNameAndPhone(String name, String phone);9
10 // SELECT * FROM user_detail WHERE name = ? OR user_id = ?11 List<UserEntity> findUserDetailsByNameOrUserId(String name, Long userId);12
13 // SELECT * FROM user_detail WHERE name IN (?, ?, ...)14 List<UserEntity> findUserDetailsByNameIn(List<String> names);15
16 // SELECT * FROM user_detail WHERE name LIKE ?17 List<UserEntity> findUserDetailsByNameLike(String namePattern);18
19 // DELETE FROM user_detail WHERE name = ?20 @Transactional21 void deleteUserDetailsByName(String name);22}Code Examples
◆ Example 1 Simple Find by Name
1// Repository2List<UserEntity> findUserDetailsByName(String name);Generated SQL:
1SELECT * FROM user_detail WHERE name = ?Usage in Service:
1List<UserEntity> users = userRepository.findUserDetailsByName("Alice");◆ Example 2 Find with AND / OR
1// AND condition2List<UserEntity> findUserDetailsByNameAndPhone(String name, String phone);3
4// OR condition5List<UserEntity> findUserDetailsByNameOrUserId(String name, Long userId);Generated SQL (AND):
1SELECT * FROM user_detail WHERE name = ? AND phone = ?Generated SQL (OR):
1SELECT * FROM user_detail WHERE name = ? OR user_id = ?◆ Example 3 Find with IN
1List<UserEntity> findUserDetailsByNameIn(List<String> names);Generated SQL:
1SELECT * FROM user_detail WHERE name IN (?, ?, ...)Usage:
1List<UserEntity> users = userRepository.findUserDetailsByNameIn(List.of("Alice", "Bob", "Charlie"));◆ Example 4 Find with LIKE
1List<UserEntity> findUserDetailsByNameLike(String namePattern);Generated SQL:
1SELECT * FROM user_detail WHERE name LIKE ?Usage:
1// Caller must provide the % wildcards manually2List<UserEntity> users = userRepository.findUserDetailsByNameLike("%Ali%");findByNameContaining("Ali") instead of findByNameLike if you want JPA to automatically add % around the value.◆ Example 5 Delete by Name
1@Transactional2void deleteUserDetailsByName(String name);Generated SQL:
1DELETE FROM user_detail WHERE name = ?@Transactional. If there are 10 rows matching the name, the delete will be called for each one (individual DELETE statements per row by default).Flowchart How Derived Query Works at Startup
Limitations of Derived Queries
java
findByNameLikeAndAgeGreaterThanAndPhoneIsNotNullOrderByNameDesc(...)
`
This is technically valid but practically unmaintainable. Use JPQL (@Query`) for anything more complex.Derived queries also cannot express JOIN queries (joining multiple tables/entities). For joins, you must use JPQL.
Part 2 Pagination and Sorting
Overview
JPA provides two interfaces to support pagination and sorting of query results:
Pageable— controls which page of results to return and how many records per page.Sort— controls the ordering of results by one or more fields.
Both can be used with derived queries and JPQL queries.
Why This Concept Exists
Returning all records from a database table in one query is impractical for large datasets — it wastes memory, increases response time, and degrades performance. Pagination solves this by returning results in chunks (pages). Sorting ensures results are in a meaningful order.
Pageable Interface
Pageable is a Spring Data interface. You create a Pageable instance using PageRequest.of(pageNumber, pageSize):
- pageNumber — zero-based index (page 0 is the first page).
- pageSize — how many records appear on each page.
Example:
1Pageable pageable = PageRequest.of(0, 5); // Page 0, 5 records per pageVisualization:
110 total records: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]2
3PageRequest.of(0, 5) → [1, 2, 3, 4, 5] (Page 0)4PageRequest.of(1, 5) → [6, 7, 8, 9, 10] (Page 1)Return Types with Pagination
| Return Type | What You Get |
|---|---|
List | Just the records for that page |
Page | Records + metadata (total pages, total elements, isFirst, isLast, etc.) |
Slice | Records + hasNext (lightweight, no total count query) |
Page when you need to show "Page 3 of 12" in your UI. Use List when you only need the records. Use Slice for infinite scroll scenarios.Derived Query with Pagination
1// Repository2Page<UserEntity> findByNameStartingWith(String prefix, Pageable pageable);Pageable must be the last parameter — JPA can detect the Pageable parameter regardless of its position. However, the convention is to always place Pageable as the last parameter for readability.Service class:
1Pageable pageable = PageRequest.of(0, 5); // Get first 5 records2Page<UserEntity> result = userRepository.findByNameStartingWith("A", pageable);3
4// Extracting data from Page object5List<UserEntity> content = result.getContent(); // The actual records6long totalElements = result.getTotalElements(); // Total matching rows in DB7int totalPages = result.getTotalPages(); // Total number of pages8boolean isFirst = result.isFirst(); // Is this the first page?9boolean isLast = result.isLast(); // Is this the last page?Generated SQL (approximately):
1SELECT * FROM user_detail WHERE name LIKE 'A%' LIMIT 5 OFFSET 0;2SELECT COUNT(*) FROM user_detail WHERE name LIKE 'A%'; -- for totalElementsSort Interface
Sort controls the ordering of results. You create a Sort using Sort.by().
◆ Single Field Sort
1Sort sort = Sort.by("name").descending();2// Or:3Sort sort = Sort.by(Sort.Direction.DESC, "name");Sort.by() is the Java entity field name, not the database column name.◆ Multiple Fields, Same Direction
1Sort sort = Sort.by("name", "phone").descending();How multi-field sorting works:
- Records are first sorted by the first field (
name). - Where two records have the same value for the first field, the second field (
phone) is used as a tiebreaker. - And so on for additional fields.
Example:
1Data: [("Alice", 1), ("Alice", 3), ("Alice", 2), ("Bob", 5)]2
3Sort by name DESC, phone DESC:4→ [("Bob", 5), ("Alice", 3), ("Alice", 2), ("Alice", 1)]◆ Multiple Fields, Different Directions
When you need ascending for one field and descending for another, you must create individual Sort.Order objects:
1Sort sort = Sort.by(2 Sort.Order.asc("name"),3 Sort.Order.desc("phone")4);Pagination + Sorting Combined
Pass a Sort instance to PageRequest.of():
1Sort sort = Sort.by("name").descending();2Pageable pageable = PageRequest.of(0, 5, sort);3
4Page<UserEntity> result = userRepository.findByNameStartingWith("A", pageable);Sort-Only (No Pagination)
If you only need sorting without pagination, use Sort as a standalone parameter:
1// Repository2List<UserEntity> findByNameStartingWith(String prefix, Sort sort);3
4// Service5Sort sort = Sort.by(Sort.Order.asc("name"), Sort.Order.desc("phone"));6List<UserEntity> result = userRepository.findByNameStartingWith("A", sort);Full Code Example Pagination and Sorting
1@RestController2@RequestMapping("/users")3public class UserController {4
5 @Autowired6 private UserDetailService userDetailService;7
8 @GetMapping("/paginated")9 public Page<UserEntity> getPaginatedUsers(10 @RequestParam(defaultValue = "0") int page,11 @RequestParam(defaultValue = "5") int size,12 @RequestParam(defaultValue = "name") String sortBy,13 @RequestParam(defaultValue = "asc") String direction) {14
15 Sort sort = direction.equalsIgnoreCase("desc")16 ? Sort.by(sortBy).descending()17 : Sort.by(sortBy).ascending();18
19 Pageable pageable = PageRequest.of(page, size, sort);20 return userDetailService.getUsers("A", pageable);21 }22}1@Service2public class UserDetailService {3
4 @Autowired5 private UserDetailRepository userDetailRepository;6
7 public Page<UserEntity> getUsers(String prefix, Pageable pageable) {8 return userDetailRepository.findByNameStartingWith(prefix, pageable);9 }10}1public interface UserDetailRepository extends JpaRepository<UserEntity, Long> {2 Page<UserEntity> findByNameStartingWith(String prefix, Pageable pageable);3}Part 3 JPQL (`@Query` Annotation)
Overview
JPQL (Java Persistence Query Language) is a query language defined by the JPA specification. It is similar to SQL but operates on Java entity objects and their fields, not on database tables and columns directly.
Why This Concept Exists
Derived queries have limitations — they cannot handle complex joins, subqueries, or projections efficiently. JPQL gives you full query control while keeping the queries database-independent (since they reference entities, not tables).
JPQL vs SQL
| Aspect | SQL | JPQL |
|---|---|---|
| Works on | Database tables and columns | Java entity classes and fields |
| Table name | user_detail | UserEntity (the Java class name) |
| Column name | user_name | name (the Java field name) |
| Database-specific? | Yes | No — database independent |
| JOINs | Uses ON clause | No ON needed — JPA infers from entity relationships |
| Used with | Native DB drivers | JPA / Hibernate |
Syntax
1@Query("SELECT u FROM UserEntity u WHERE u.name = :userName")2UserEntity findByUserName(@Param("userName") String name);◆ Syntax Breakdown
| Part | Meaning |
|---|---|
@Query(...) | Annotation telling Spring Data this method uses a custom JPQL query |
"SELECT u FROM UserEntity u" | UserEntity is the Java class name (not table name). u is an alias. |
WHERE u.name | name is the Java field name in UserEntity (not the DB column name) |
:userName | A named parameter — will be replaced with the method argument |
@Param("userName") | Binds the method parameter name to the named query parameter :userName |
@Query-annotated method does not need to follow any naming convention. Only derived query methods must follow the findBy... pattern.Named Parameters vs Positional Parameters
Named parameters (recommended):
1@Query("SELECT u FROM UserEntity u WHERE u.name = :name AND u.phone = :phone")2List<UserEntity> findByNameAndPhone(@Param("name") String name, @Param("phone") String phone);Positional parameters (older style):
1@Query("SELECT u FROM UserEntity u WHERE u.name = ?1 AND u.phone = ?2")2List<UserEntity> findByNameAndPhone(String name, String phone);:name + @Param) over positional parameters (?1) for readability and maintainability.Return Types in JPQL
List<>), JPA will throw a NonUniqueResultException at runtime. Always choose your return type based on the expected number of results.| Query result | Correct return type |
|---|---|
| Always one row | UserEntity or Optional |
| Zero or one row | Optional |
| Multiple rows | List |
| Count | long |
Code Examples
◆ Example 1 Simple SELECT with Named Parameter
1@Query("SELECT u FROM UserEntity u WHERE u.name = :userName")2Optional<UserEntity> findByUserName(@Param("userName") String name);Generated SQL:
1SELECT * FROM user_detail WHERE name = ?◆ Example 2 SELECT with JOIN (One-to-One)
Entity setup:
1@Entity2public class UserEntity {3 @Id4 private Long id;5 private String name;6
7 @OneToOne8 @JoinColumn(name = "address_id")9 private UserAddress userAddress;10}Repository:
1@Query("SELECT ud FROM UserEntity ud JOIN ud.userAddress WHERE ud.name = :name")2List<UserEntity> findUsersWithAddress(@Param("name") String name);Generated SQL:
1SELECT ud.* FROM user_detail ud2JOIN user_address ua ON ud.address_id = ua.id3WHERE ud.name = ?ON clause. JPA automatically infers the join condition from the entity relationship mapping (@JoinColumn, @OneToOne, etc.).◆ Example 3 Selecting Specific Fields (Projection) Object Array
When you want to return only specific fields from one or multiple entities:
1@Query("SELECT ud.name, ua.country FROM UserEntity ud JOIN ud.userAddress ua WHERE ud.name = :name")2List<Object[]> findNameAndCountry(@Param("name") String name);Service usage:
1List<Object[]> results = userRepository.findNameAndCountry("Alice");2List<UserDTO> dtos = new ArrayList<>();3
4for (Object[] row : results) {5 String name = (String) row[0];6 String country = (String) row[1];7 dtos.add(new UserDTO(name, country));8}Object[] works but is error-prone — you must remember the column order and cast types manually. Prefer the constructor expression approach below.◆ Example 4 Selecting Specific Fields Using Constructor Expression (Recommended)
Instead of returning Object[], you can return a DTO (Data Transfer Object) directly from the JPQL query:
DTO class:
1public class UserDTO {2 private String name;3 private String country;4
5 // Constructor used by JPQL6 public UserDTO(String name, String country) {7 this.name = name;8 this.country = country;9 }10 // getters...11}Repository:
1@Query("SELECT new com.example.dto.UserDTO(ud.name, ua.country) " +2 "FROM UserEntity ud JOIN ud.userAddress ua WHERE ud.name = :name")3List<UserDTO> findUserDTOs(@Param("name") String name);new expression. For each row returned by the query, JPQL calls the DTO constructor with the values from that row.Service usage:
1List<UserDTO> dtos = userRepository.findUserDTOs("Alice");2// No manual parsing needed — dtos is ready to use◆ Example 5 Multiple Table JOINs
1// Table A → Table B → Table C2@Query("SELECT a FROM TableA a JOIN a.bList b JOIN b.cList c WHERE a.name = :name")3List<TableA> findWithBAndC(@Param("name") String name);Each additional table requires one more JOIN. No ON clause is needed at any level — JPA infers the join conditions from the entity mappings.
JPQL with Pagination and Sorting
Pagination and sorting work identically with @Query methods as with derived query methods — just add Pageable or Sort as a parameter:
1@Query("SELECT u FROM UserEntity u WHERE u.name = :name")2Page<UserEntity> findByName(@Param("name") String name, Pageable pageable);1// Service2Pageable pageable = PageRequest.of(0, 5, Sort.by("name").descending());3Page<UserEntity> page = userRepository.findByName("Alice", pageable);Part 4 The N+1 Problem
Overview
The N+1 problem is a performance issue that occurs in JPA when fetching a parent entity and its associated child entities results in 1 query for all parents + N additional queries (one per parent) for the children, instead of a single efficient query.
Why It Happens
This stems from how JPA handles lazy and eager loading when dealing with one-to-many and many-to-many relationships.
Background — Eager vs Lazy loading:
- Lazy loading: When you load a parent, child entities are not loaded. They are loaded on demand (when you first access them in code).
- Eager loading: When you load a parent, child entities are loaded immediately along with the parent.
The trap:
- Eager loading works as expected when fetching a single parent — JPA generates one joined query that fetches the parent and all its children together.
- When your query can return multiple parents, JPA changes its behavior for performance reasons: it first fetches all parents in one query, then fires one additional SELECT per parent to fetch that parent's children.
- This is true even with
FetchType.EAGER.
Definition
The N+1 Problem is a query performance anti-pattern where loading N parent entities results in N additional database queries (one per parent) to load their child entities, for a total of N+1 database round-trips instead of 1.
Real-World Analogy
Imagine going to a library to find all books by authors whose name starts with "A".
- Without N+1 fix: You first go to the author index and get a list of 50 authors (1 trip). Then, for each of the 50 authors, you make a separate trip to the shelf to get their books (50 trips). Total: 51 trips.
- With the fix: You ask the librarian to bring you all books by all matching authors in one trip. Total: 1 trip.
Example Setup
1@Entity2public class UserEntity {3 @Id4 private Long id;5 private String name;6
7 @OneToMany(fetch = FetchType.EAGER)8 private List<UserAddress> userAddressList;9}Query:
1@Query("SELECT ud FROM UserEntity ud JOIN ud.userAddressList WHERE ud.name = :name")2List<UserEntity> findUsersWithAddresses(@Param("name") String name);Scenario: 2 users in DB, each with 1 address.
Actual SQL generated:
1-- Query 1: Fetch all matching users2SELECT * FROM user_detail WHERE name = 'A';3
4-- Query 2: Fetch addresses for user ID 15SELECT * FROM user_address WHERE user_id = 1;6
7-- Query 3: Fetch addresses for user ID 28SELECT * FROM user_address WHERE user_id = 2;Total: 3 queries = 1 + N (where N = 2 users)
If there were 100 users, there would be 101 queries.
Flowchart N+1 Problem
Solutions to the N+1 Problem
There are three main solutions, each applicable to different scenarios.
◆ Solution 1 `JOIN FETCH` in JPQL
Use JOIN FETCH instead of JOIN. This tells JPA to fetch the parent and all children in a single SQL query.
1@Query("SELECT ud FROM UserEntity ud JOIN FETCH ud.userAddressList WHERE ud.name = :name")2List<UserEntity> findUsersWithAddressesFetch(@Param("name") String name);Generated SQL:
1SELECT ud.*, ua.* FROM user_detail ud2INNER JOIN user_address ua ON ua.user_id = ud.id3WHERE ud.name = ?One query. All parent and child data loaded together.
ud (user details), JOIN FETCH forces JPA to also retrieve ua (addresses) in the same query and populate the userAddressList collection on each UserEntity.◆ Solution 2 `@BatchSize`
Applicable when you are using derived queries (where you cannot write JOIN FETCH) or want to reduce N+1 without eliminating it entirely.
1@Entity2public class UserEntity {3 @Id4 private Long id;5 private String name;6
7 @OneToMany(fetch = FetchType.EAGER)8 @BatchSize(size = 10) // Fetch children in batches of 109 private List<UserAddress> userAddressList;10}How it works:
- Instead of N separate queries (one per parent), JPA groups the child fetches into batches.
- With
@BatchSize(size = 10)and 50 parents: 1 query for all parents + ceil(50/10) = 5 batch queries for children = 6 queries total (instead of 51).
@BatchSize reduces the N+1 problem but does not eliminate it. It goes from N+1 queries to approximately (N/batchSize) + 1 queries. Use JOIN FETCH for the best performance when a single query is viable.◆ Solution 3 `@EntityGraph`
Applicable for derived query methods where you cannot write custom JPQL.
1// On the entity2@Entity3@NamedEntityGraph(4 name = "UserEntity.withAddresses",5 attributeNodes = @NamedAttributeNode("userAddressList")6)7public class UserEntity {8 ...9 @OneToMany10 private List<UserAddress> userAddressList;11}12
13// In the repository14@EntityGraph(attributePaths = {"userAddressList"})15List<UserEntity> findByName(String name);@EntityGraph tells JPA: "Even though this is just a findByName query, eagerly fetch userAddressList alongside the main entity in a single query."
Comparison of N+1 Solutions
| Solution | Eliminates N+1 Completely? | Works with Derived Queries? | Works with JPQL? |
|---|---|---|---|
JOIN FETCH | ✅ Yes — single query | ❌ No | ✅ Yes |
@BatchSize | ❌ No — reduces it | ✅ Yes | ✅ Yes |
@EntityGraph | ✅ Yes — single query | ✅ Yes | ✅ Yes |
Why Eager Loading Alone Doesn't Solve N+1
FetchType.EAGER will always generate a single JOIN query. This is incorrect.
Eager loading generates a joined query ONLY when fetching a single parent (e.g., findById()).
When your query can return multiple parents (e.g., findAll(), findByName() returning a list), JPA abandons the join approach for performance optimization reasons and instead falls back to N+1 behavior — fetching all parents first, then fetching children per parent.
This is why JOIN FETCH, @BatchSize, or @EntityGraph must be explicitly used.Part 5 `@Modifying` Annotation
Overview
By default, JPQL assumes every query written inside @Query is a SELECT (read) operation. If you write a DELETE, UPDATE, or INSERT query inside @Query without additional annotation, JPA will throw an error at runtime.
The @Modifying annotation tells JPA that the query modifies the database (i.e., it is not a SELECT).
Definition
@Modifyingis a Spring Data JPA annotation that marks a@Query-annotated method as a data-modifying operation (UPDATE, DELETE, or INSERT). Without it, JPA will reject non-SELECT JPQL queries.
Syntax
1@Modifying2@Transactional3@Query("DELETE FROM UserEntity u WHERE u.name = :name")4void deleteByUserName(@Param("name") String name);1@Modifying2@Transactional3@Query("UPDATE UserEntity u SET u.phone = :phone WHERE u.name = :name")4int updatePhoneByName(@Param("phone") String phone, @Param("name") String name);@Modifying must always be used together with @Transactional. Since you are modifying the database, a transaction is required. Without @Transactional, Spring will throw TransactionRequiredException.The `flushAutomatically` and `clearAutomatically` Problem
This is a subtle but important concept that arises when using @Modifying with JPQL queries within the same transaction that also performs reads.
The Problem:
Consider this sequence within a single transaction:
1@Transactional2public void deleteAndVerify(Long id, String name) {3 // Step 1: Load the entity — stored in Persistence Context4 UserEntity user = userRepository.findById(id).get();5
6 // Step 2: Delete via @Modifying JPQL — DB record deleted7 userRepository.deleteByUserName(name);8
9 // Step 3: Try to find the entity again10 Optional<UserEntity> found = userRepository.findById(id);11 System.out.println(found.isPresent()); // ← What prints here?12}What actually prints: true
Why:
- Step 1 loads the entity into the Persistence Context (first-level cache).
- Step 2's
@ModifyingDELETE goes directly to the database via JPQL, bypassing the Persistence Context. - The DB record is deleted, but the Persistence Context still holds the old entity.
- Step 3's
findById()checks the Persistence Context first → finds the cached entity → returns it → printstrue.
This is a stale read — the Persistence Context is out of sync with the database.
The Solution: flushAutomatically = true and clearAutomatically = true
1@Modifying(flushAutomatically = true, clearAutomatically = true)2@Transactional3@Query("DELETE FROM UserEntity u WHERE u.name = :name")4void deleteByUserName(@Param("name") String name);| Option | What it does |
|---|---|
flushAutomatically = true | Before executing the modifying query, flush any pending Persistence Context changes to the DB (sync PC → DB). |
clearAutomatically = true | After executing the modifying query, clear the Persistence Context (remove all cached entities). |
With these options set:
clearAutomatically = trueremoves all entities from the Persistence Context after the DELETE.- Step 3's
findById()finds an empty Persistence Context → goes to the DB → DB has no record → returnsOptional.empty()→ printsfalse.
clearAutomatically = true: Any time you use @Modifying with a JPQL query that modifies data, and you will subsequently read the same data within the same transaction. Without it, you risk stale reads from the Persistence Context.Flush vs Clear Clarification
| Operation | Effect on PC | Effect on DB |
|---|---|---|
flush | PC data is written to DB (sync) | DB is updated |
clear | All entities removed from PC (detached) | DB unchanged |
flush + clear | PC changes written to DB, then PC emptied | DB updated, PC empty |
Part 6 `@NamedQuery` Annotation
Overview
@NamedQuery allows you to define a reusable JPQL query at the entity class level and reference it by name anywhere in your codebase.
Why This Concept Exists
If the same query is used in multiple places in your codebase (multiple repositories or multiple methods), duplicating the query string is a maintenance problem. If the query needs to change, you must update it in every place it appears. @NamedQuery centralizes the query definition.
Definition
@NamedQueryis a JPA annotation placed on an entity class that defines a named JPQL query. The query can be referenced by name from any repository, avoiding duplication and centralizing query management.
Syntax
On the entity class:
1@Entity2@NamedQuery(3 name = "UserEntity.findByUsername",4 query = "SELECT u FROM UserEntity u WHERE u.name = :name"5)6public class UserEntity {7 @Id8 private Long id;9 private String name;10 // ...11}In the repository:
1public interface UserDetailRepository extends JpaRepository<UserEntity, Long> {2
3 // Method name must match the name defined in @NamedQuery: "UserEntity.findByUsername"4 // No @Query annotation needed — Spring Data finds the @NamedQuery by convention5 List<UserEntity> findByUsername(@Param("name") String name);6}@NamedQuery named . . So a method named findByUsername on a UserEntity repository will automatically match a @NamedQuery named "UserEntity.findByUsername".Multiple Named Queries
Use @NamedQueries (plural) to define multiple named queries on one entity:
1@Entity2@NamedQueries({3 @NamedQuery(name = "UserEntity.findByUsername", query = "SELECT u FROM UserEntity u WHERE u.name = :name"),4 @NamedQuery(name = "UserEntity.findActiveUsers", query = "SELECT u FROM UserEntity u WHERE u.active = true")5})6public class UserEntity { ... }Benefits of `@NamedQuery`
- Single source of truth — query defined once, reused everywhere.
- Validated at startup — JPA validates all
@NamedQueryqueries when the application starts. Errors are caught early, not at runtime. - Performance — named queries can be pre-compiled by the JPA provider at startup.
Architecture Diagram All Query Mechanisms
Mind Map All Topics
Common Mistakes
Mistake 1 Missing `@Transactional` on Delete Derived Query
1// WRONG — will throw TransactionRequiredException2void deleteUserDetailsByName(String name);3
4// CORRECT5@Transactional6void deleteUserDetailsByName(String name);Mistake 2 Wrong Field Name in Derived Query
1// WRONG — 'username' is not a field in UserEntity; field is 'name'2List<UserEntity> findByUsername(String name); // Exception at startup3
4// CORRECT5List<UserEntity> findByName(String name);PropertyReferenceException.Mistake 3 Using Table/Column Names in JPQL
1// WRONG — using table name and column name (SQL style)2@Query("SELECT * FROM user_detail WHERE user_name = :name")3
4// CORRECT — using entity class name and field name (JPQL style)5@Query("SELECT u FROM UserEntity u WHERE u.name = :name")Mistake 4 Missing `@Modifying` on Update/Delete Query
1// WRONG — JPA expects SELECT by default2@Query("DELETE FROM UserEntity u WHERE u.name = :name")3void deleteByUserName(@Param("name") String name); // Throws exception4
5// CORRECT6@Modifying7@Transactional8@Query("DELETE FROM UserEntity u WHERE u.name = :name")9void deleteByUserName(@Param("name") String name);Mistake 5 Stale Read After `@Modifying` Without `clearAutomatically`
1// WRONG — may return stale data from Persistence Context after delete2@Modifying3@Transactional4@Query("DELETE FROM UserEntity u WHERE u.name = :name")5void deleteByUserName(@Param("name") String name);6
7// CORRECT — clears Persistence Context after modification8@Modifying(flushAutomatically = true, clearAutomatically = true)9@Transactional10@Query("DELETE FROM UserEntity u WHERE u.name = :name")11void deleteByUserName(@Param("name") String name);Mistake 6 Assuming Eager Loading Prevents N+1
1// WRONG assumption: FetchType.EAGER always generates one query2@OneToMany(fetch = FetchType.EAGER)3private List<UserAddress> userAddressList;4// When query returns multiple parents → still N+1 behavior!5
6// CORRECT: Use JOIN FETCH or @EntityGraph7@Query("SELECT ud FROM UserEntity ud JOIN FETCH ud.userAddressList WHERE ud.name = :name")8List<UserEntity> findUsers(@Param("name") String name);Best Practices
- Use derived queries for simple cases. If your condition is one or two fields, a derived query is the cleanest solution.
- Switch to
@Query(JPQL) when derived queries become unreadable. A method name likefindByNameAndAgeGreaterThanAndPhoneIsNotNullOrderByNameDescis valid but unmaintainable.
- Always use named parameters (
:param+@Param) in JPQL. Positional parameters (?1) are fragile — reordering method parameters breaks the query silently.
- Always add
@Transactionalto modifying operations (@Modifying, delete-derived queries).
- Use
clearAutomatically = truewith@Modifyingwhenever you read data after a JPQL modification within the same transaction.
- Prefer
JOIN FETCHover@BatchSizewhen you need to completely eliminate N+1. Use@BatchSizeonly as a fallback whenJOIN FETCHis not feasible.
- Use
Pageas return type only when you actually need pagination metadata (total pages, total elements). UseListotherwise —Pagealways fires an extraCOUNT(*)query.
- Put
Pageableas the last parameter in repository methods by convention, even though JPA does not strictly require it.
- Use constructor expressions in JPQL (the
new com.example.DTO(...)syntax) instead ofObject[]for cleaner, type-safe projections.
- Use
@NamedQueryfor queries shared across multiple repositories to avoid duplication and benefit from startup-time validation.
Interview Notes
Frequently Asked Questions
Q: What is a derived query in Spring Data JPA?
A: A derived query is a repository method whose JPQL query is automatically generated by Spring Data JPA by parsing the method name. The method name must follow a strict naming convention starting with prefixes like find, delete, count, followed by By and field names with optional keywords like And, Or, Like, In, etc.
Q: What is the difference between JPQL and SQL?
A: JPQL operates on Java entity classes and their field names, while SQL operates on database tables and column names. JPQL is database-independent — you can switch databases without changing JPQL queries.
Q: What is the N+1 problem? How do you solve it?
A: When fetching N parent entities that each have child collections, JPA may fire 1 query for parents and then N additional queries (one per parent) for children — totaling N+1 queries. Solutions: (1) JOIN FETCH in JPQL, (2) @BatchSize on the collection, (3) @EntityGraph annotation.
Q: What does @Modifying do?
A: It tells Spring Data JPA that the associated @Query performs a data-modification operation (UPDATE, DELETE, INSERT) rather than a SELECT. Without it, JPA rejects non-SELECT queries.
Q: What is clearAutomatically in @Modifying?
A: It clears the Persistence Context (first-level cache) after executing the modifying query. This prevents stale reads — without it, a subsequent findById() in the same transaction may return the old cached entity even after it was deleted from the DB.
Q: Why does FetchType.EAGER not always prevent N+1?
A: Eager loading generates a JOIN query only when fetching a single parent. When a query can return multiple parents, JPA reverts to fetching all parents first, then fetching children per parent (N+1), as a performance optimization measure.
Q: When would you use @NamedQuery?
A: When the same JPQL query needs to be reused across multiple repository methods or repositories. It centralizes the query, making future changes easier, and JPA validates it at startup rather than at runtime.
Q: What is the difference between Page and List return types in pagination?
A: Page includes metadata like total number of pages, total elements, whether it's the first or last page. It fires an additional COUNT(*) query automatically. List returns only the records for the page. Use Page when you need pagination metadata, List otherwise.
Practice Questions
Easy
- Write a derived query method to find all users where the phone number is not null.
- Write a derived query to delete all users by a given name. What annotation must be added?
- What prefixes can a derived query method start with?
- What does
PageRequest.of(2, 10)mean? - What annotation do you use to write a custom JPQL query in a repository method?
Medium
- Write a
@QueryJPQL method to find users by name and return only theirnameandcountry(from the relatedUserAddress) as aListusing a constructor expression. - Explain what happens without
clearAutomatically = truewhen you delete an entity via@Modifyingand then callfindById()in the same transaction. - Write a repository method that finds users whose names start with "A", sorted by name descending, returning page 0 with 5 items per page.
- Why does
FetchType.EAGERon a@OneToManyfield still result in N+1 queries when fetching multiple parents? - What is the difference between
flushandclearin the context of Persistence Context?
Hard
- You have
UserEntitywith a@OneToManylist ofOrderEntity, each with a@OneToManylist ofOrderItemEntity. Write a JPQL query usingJOIN FETCHto fetch all users along with their orders and order items in a single query. - Design a repository method that: (a) uses a custom JPQL query, (b) accepts pagination with sorting, (c) uses constructor expression to return a DTO, and (d) avoids N+1. Write the entity, DTO, repository method, and service call.
- Explain why
@BatchSizedoes not completely eliminate the N+1 problem but can significantly reduce database round-trips. Calculate the number of queries for 47 parents with@BatchSize(size = 10).
Summary
- Derived Queries — auto-generate SQL from method names using naming conventions (
findBy,deleteBy,countBy+ field names + keywords likeAnd,Or,Like,In,Between). No@Queryneeded. Limited to simple conditions.
- JPQL — full query language using entity class and field names (not DB table/column names). Specified via
@Query. Database-independent. Supports joins (noONneeded), projections, constructor expressions,@Parambinding.
- Pagination — use
Pageable(viaPageRequest.of(page, size)). ReturnPagefor metadata,Listfor records only. PassPageableas a method parameter.
- Sorting — use
Sort.by(field).direction(). Combine withPageableviaPageRequest.of(page, size, sort). UseSort.Orderfor per-field direction control. Field names are Java entity field names.
- N+1 Problem — occurs when fetching multiple parents with child collections results in 1 parent query + N child queries. Fix with
JOIN FETCH(best),@EntityGraph, or@BatchSize(partial fix). Eager loading alone does not prevent N+1 for multi-parent queries.
@Modifying— required for JPQL UPDATE/DELETE/INSERT queries. Must be paired with@Transactional. UseclearAutomatically = trueto prevent stale Persistence Context reads after modification.
@NamedQuery— defined on the entity class. Centralizes reusable queries. Validated at startup. Referenced by name in repository methods.
Mastery check
How well can you recall this?
Finished this lesson?