JPA Part 4 — Native Queries & Criteria API
Native SQL queries, stored procedures, Criteria API, dynamic queries with CriteriaBuilder
- Use native queries for database-specific SQL
- Build type-safe dynamic queries with the Criteria API
- Compare JPQL, native SQL, and Criteria API trade-offs
Series:
Concept and Coding — JPA Series Part: 4 — Custom Queries Prerequisites: JPA Parts 1–3 (Architecture, Entity Mappings, JPQL basics)
Table of Contents
- Native Queries — Overview
- JPQL vs Native Query — When to Use Which
- Writing a Basic Native Query
- Returning Partial Fields — Mapping Strategies
- Dynamic Native Queries
- Pagination and Sorting in Native Queries
- Why Criteria API Exists — The Gap
- Criteria API — Architecture & Hierarchy
- Criteria API — Step-by-Step: Select All Fields
- Criteria API — Predicates (Where Conditions)
- Criteria API — Selecting Specific Fields (Multi-Select)
- Criteria API — Joins
- Criteria API — Pagination and Sorting
- Comparison Table — JPQL vs Native Query vs Criteria API
- Common Mistakes & Best Practices
- Interview Notes
- Practice Questions
- Summary
1. Native Queries Overview
What Is a Native Query?
A Native Query is a plain SQL query written exactly as you would write it in a SQL client (MySQL Workbench, pgAdmin, etc.) and executed directly against the database through JPA.
Unlike JPQL, which operates on Java entities, native queries operate on actual database tables and columns.
Key Characteristics
| Property | Behaviour |
|---|---|
| Language | Plain SQL (database-specific syntax) |
| Operates on | Actual table names and column names (not Java entity names) |
| Caching | No Persistence Context (L1) caching |
| Entity lifecycle | Not managed — JPA does not track entities fetched via native queries |
| DB portability | Not portable — tied to the specific database dialect |
| Dynamic queries | Supported (via EntityManager.createNativeQuery()) |
Trade-offs
2. JPQL vs Native Query When to Use Which
Use JPQL When:
- Queries are straightforward CRUD operations on entities
- You need JPA's first-level caching (Persistence Context)
- You want database-independent code (future DB migration safety)
- Entity lifecycle management is important
Use Native Query When:
| Use Case | Reason JPQL Cannot Handle It |
|---|---|
| Querying JSONB / JSON columns | JPQL has no concept of JSON column operations |
| Unrelated entity joins | JPQL joins require defined entity relationships |
Aggregations like COUNT(*) AS cnt returning non-entity results | JPQL must return entity fields or mapped types |
| Complex DB-specific functions (window functions, CTEs, etc.) | JPQL does not support database-specific SQL extensions |
| Bulk operations requiring raw speed | Native queries bypass entity management overhead |
3. Writing a Basic Native Query
Syntax Comparison
JPQL query:
1@Query("SELECT u FROM UserDetails u WHERE u.name = :name")2List<UserDetails> findByName(@Param("name") String name);Native query — same operation:
1@Query(2 value = "SELECT * FROM user_details WHERE user_name = :name",3 nativeQuery = true // ← This is the only addition4)5List<UserDetails> findByNameNative(@Param("name") String name);Critical Difference: Entity Names vs Table Names
| Context | Use |
|---|---|
| JPQL | Java entity class name (UserDetails) and Java field names (name, phone) |
| Native Query | Actual DB table name (user_details) and actual DB column names (user_name, phone_number) |
name maps to DB column user_name, you must write user_name in the native query.Full Example with Entity and Repository
1// Entity2@Entity3@Table(name = "user_details")4public class UserDetails {5
6 @Id7 @GeneratedValue(strategy = GenerationType.IDENTITY)8 private Long id;9
10 @Column(name = "user_name") // DB column: user_name, Java field: name11 private String name;12
13 @Column(name = "phone_number") // DB column: phone_number, Java field: phone14 private String phone;15
16 public UserDetails() {}17 // Getters and Setters...18}19
20// Repository21@Repository22public interface UserDetailRepository extends JpaRepository<UserDetails, Long> {23
24 // Native query: uses DB table name and DB column names25 @Query(26 value = "SELECT * FROM user_details WHERE user_name = :name",27 nativeQuery = true28 )29 List<UserDetails> findByNameNative(@Param("name") String name);30}How Does `SELECT *` Mapping Work Automatically?
When you use SELECT * in a native query and the return type is an entity:
- JPA retrieves all columns from the result set
- JPA automatically maps DB column names → Java entity field names using the
@Column(name=...)annotations - You get a fully populated entity object
This mapping is automatic only for SELECT * (all fields). For partial fields, you must handle mapping explicitly — covered in the next section.
4. Returning Partial Fields Mapping Strategies
When you write a native query that returns only some columns (not SELECT *), JPA cannot automatically map the result to an entity — because the entity expects all fields, and some will be missing.
Problem:
1@Query(2 value = "SELECT user_name, phone_number FROM user_details WHERE user_name = :name",3 nativeQuery = true4)5List<UserDetails> findPartialNative(@Param("name") String name);6// ❌ Throws: Column 'id' not found — JPA tries to map all entity fields but id is missingSolution: You need a DTO (Data Transfer Object) and one of two mapping strategies.
4.1 Strategy 1: SQL Result Set Mapping
This is the annotation-based approach using @NamedNativeQuery and @SqlResultSetMapping. Both annotations are placed on the entity class.
◆ Step 1: Create the DTO
1public class UserDTO {2
3 private String name;4 private String phone;5
6 // Constructor matching the fields returned by the query (ORDER MATTERS)7 public UserDTO(String name, String phone) {8 this.name = name;9 this.phone = phone;10 }11
12 // Getters13 public String getName() { return name; }14 public String getPhone() { return phone; }15}◆ Step 2: Annotate the Entity with `@NamedNativeQuery` and `@SqlResultSetMapping`
1@Entity2@Table(name = "user_details")3
4// Step 2a: Define the named native query5@NamedNativeQuery(6 name = "UserDetails.findNameAndPhone", // Logical name for this query7 query = "SELECT user_name, phone_number FROM user_details WHERE user_name = :name",8 resultSetMapping = "UserDTOMapping" // Points to the mapping below9)10
11// Step 2b: Define how to map the query result to a DTO12@SqlResultSetMapping(13 name = "UserDTOMapping", // Must match resultSetMapping above14 classes = @ConstructorResult(15 targetClass = UserDTO.class, // Which DTO class to instantiate16 columns = {17 @ColumnResult(name = "user_name", type = String.class), // 1st constructor arg18 @ColumnResult(name = "phone_number", type = String.class) // 2nd constructor arg19 }20 )21)22public class UserDetails {23 // ... entity fields as usual24}◆ Step 3: Use the Named Query in the Repository
1@Repository2public interface UserDetailRepository extends JpaRepository<UserDetails, Long> {3
4 // Reference the named query by its logical name5 // No need to write the SQL again6 @Query(7 name = "UserDetails.findNameAndPhone", // The name given in @NamedNativeQuery8 nativeQuery = true9 )10 List<UserDTO> findNameAndPhone(@Param("name") String name);11}◆ How It Works Internally
@NamedNativeQuery and @SqlResultSetMapping annotations must be placed on an entity class, not on the repository or DTO. This is a JPA requirement.4.2 Strategy 2: Object Array Manual Mapping
This is the programmatic approach — simpler to set up but requires manual mapping code in the service layer.
◆ Step 1: Repository Returns `List<Object[]>`
1@Repository2public interface UserDetailRepository extends JpaRepository<UserDetails, Long> {3
4 @Query(5 value = "SELECT user_name, phone_number FROM user_details WHERE user_name = :name",6 nativeQuery = true7 )8 List<Object[]> findNameAndPhoneRaw(@Param("name") String name);9 // Each Object[] represents one row10 // Object[0] = user_name value11 // Object[1] = phone_number value12}◆ Step 2: Service Layer Maps `Object[]` to DTO
1@Service2public class UserService {3
4 @Autowired5 private UserDetailRepository userRepo;6
7 public List<UserDTO> getUserNameAndPhone(String name) {8 List<Object[]> rawResults = userRepo.findNameAndPhoneRaw(name);9
10 return rawResults.stream()11 .map(row -> new UserDTO(12 (String) row[0], // user_name → UserDTO.name13 (String) row[1] // phone_number → UserDTO.phone14 ))15 .collect(Collectors.toList());16 }17}Comparison: Two Partial Field Strategies
| Aspect | SQL Result Set Mapping | Object Array Manual |
|---|---|---|
| Setup location | Entity class annotations | Service class code |
| Boilerplate | More annotations, less service code | Less annotations, more service code |
| Type safety | Moderate | Low (raw Object[]) |
| Flexibility | Less — tied to annotations | More — can transform in code |
| Readability | Annotations can be verbose | Service code is explicit |
| Best for | Stable, reused queries | Ad-hoc or rarely used queries |
SELECT *, do so — JPA handles the mapping automatically. Use partial field strategies only when you genuinely need a subset of columns (for performance or security reasons).5. Dynamic Native Queries
What Is a Dynamic Query?
A dynamic query is one where the WHERE clause conditions are built at runtime based on what parameters the caller provides. Some parameters may or may not be present.
Example scenario:
- If
usernameis provided → addAND user_name = ? - If
phoneis provided → addAND phone_number = ? - If neither → return all records
- If both → filter by both
JPQL has no native support for this pattern. The JPA solution is the Criteria API (covered later). For native SQL, you build the query string dynamically using EntityManager.createNativeQuery().
Implementation with EntityManager
1@Service2public class UserService {3
4 @PersistenceContext5 private EntityManager entityManager;6
7 public List<UserDTO> searchUsers(String username, String phone) {8
9 // Step 1: Start building the SQL string10 StringBuilder queryBuilder = new StringBuilder();11 queryBuilder.append("SELECT user_name, phone_number FROM user_details ");12 queryBuilder.append("WHERE 1=1 "); // Trick: always-true condition so we can safely append "AND ..."13
14 // Step 2: Maintain a list of parameter values in the order they appear as ?15 List<Object> parameters = new ArrayList<>();16
17 // Step 3: Dynamically append conditions based on input18 if (username != null && !username.isEmpty()) {19 queryBuilder.append("AND user_name = ? ");20 parameters.add(username); // Position 1 → replaces first ?21 }22
23 if (phone != null && !phone.isEmpty()) {24 queryBuilder.append("AND phone_number = ? ");25 parameters.add(phone); // Position 2 → replaces second ?26 }27
28 // Step 4: Create the native query from the built string29 Query nativeQuery = entityManager.createNativeQuery(queryBuilder.toString());30
31 // Step 5: Replace ? placeholders with actual values (1-based index)32 for (int i = 0; i < parameters.size(); i++) {33 nativeQuery.setParameter(i + 1, parameters.get(i)); // JPA uses 1-based index34 }35
36 // Step 6: Execute and get results37 List<Object[]> rawResults = nativeQuery.getResultList();38
39 // Step 7: Map Object[] to DTO40 return rawResults.stream()41 .map(row -> new UserDTO((String) row[0], (String) row[1]))42 .collect(Collectors.toList());43 }44}The `WHERE 1=1` Pattern Explained
1// WITHOUT the 1=1 trick — complexity:2String query = "SELECT * FROM user_details ";3boolean firstCondition = true;4
5if (username != null) {6 query += "WHERE user_name = ? "; // Must add WHERE before first condition7 firstCondition = false;8}9if (phone != null) {10 if (firstCondition) {11 query += "WHERE phone_number = ? "; // If first condition, need WHERE12 } else {13 query += "AND phone_number = ? "; // If not first, need AND14 }15}16// Messy! Must track whether WHERE has been added yet17
18// WITH the 1=1 trick — clean:19String query = "SELECT * FROM user_details WHERE 1=1 ";20if (username != null) query += "AND user_name = ? "; // Always just AND21if (phone != null) query += "AND phone_number = ? "; // Always just AND22// Clean! WHERE is always present; conditions are always ANDWHERE 1=1 is a widely used SQL pattern for building dynamic queries. 1=1 always evaluates to true and costs nothing in the DB optimizer — it is immediately eliminated by the query planner.Dynamic Query Flow
6. Pagination and Sorting in Native Queries
Method A: Dynamic Native Query (Manual SQL)
When building queries dynamically with EntityManager, you add ORDER BY, LIMIT, and OFFSET directly to the SQL string:
1public List<UserDTO> searchUsersPaged(2 String username,3 int pageNumber, // 0-based (page 0, 1, 2...)4 int pageSize, // records per page5 String sortField, // e.g. "phone_number"6 String sortDir // "ASC" or "DESC"7) {8 StringBuilder queryBuilder = new StringBuilder();9 queryBuilder.append("SELECT user_name, phone_number FROM user_details WHERE 1=1 ");10
11 List<Object> parameters = new ArrayList<>();12
13 if (username != null && !username.isEmpty()) {14 queryBuilder.append("AND user_name = ? ");15 parameters.add(username);16 }17
18 // Sorting — append ORDER BY19 queryBuilder.append("ORDER BY ").append(sortField).append(" ").append(sortDir).append(" ");20
21 // Pagination — append LIMIT and OFFSET22 queryBuilder.append("LIMIT ? OFFSET ? ");23 parameters.add(pageSize); // ? → LIMIT (records per page)24 parameters.add(pageNumber * pageSize); // ? → OFFSET (records to skip)25
26 Query nativeQuery = entityManager.createNativeQuery(queryBuilder.toString());27
28 for (int i = 0; i < parameters.size(); i++) {29 nativeQuery.setParameter(i + 1, parameters.get(i));30 }31
32 List<Object[]> rawResults = nativeQuery.getResultList();33 return rawResults.stream()34 .map(row -> new UserDTO((String) row[0], (String) row[1]))35 .collect(Collectors.toList());36}sortField directly into SQL without validation — this opens an SQL injection vulnerability. Always validate sortField against an allowlist of permitted column names before appending.1// Safe pattern: validate sortField against allowlist2private static final Set<String> ALLOWED_SORT_FIELDS = Set.of("user_name", "phone_number", "id");3
4if (!ALLOWED_SORT_FIELDS.contains(sortField)) {5 throw new IllegalArgumentException("Invalid sort field: " + sortField);6}Method B: `@Query` with `nativeQuery = true` + `Pageable`
When using the @Query annotation approach (non-dynamic), JPA handles pagination automatically — you just add a Pageable parameter:
1@Repository2public interface UserDetailRepository extends JpaRepository<UserDetails, Long> {3
4 @Query(5 value = "SELECT * FROM user_details WHERE phone_number = :phone",6 countQuery = "SELECT COUNT(*) FROM user_details WHERE phone_number = :phone",7 nativeQuery = true8 )9 Page<UserDetails> findByPhone(@Param("phone") String phone, Pageable pageable);10}1// Calling the paginated query from service2@Service3public class UserService {4
5 @Autowired6 private UserDetailRepository userRepo;7
8 public Page<UserDetails> getUsersByPhone(String phone, int page, int size) {9 // Sort descending by phone_number, page 0, 5 records per page10 Pageable pageable = PageRequest.of(11 page, // page number (0-based)12 size, // page size13 Sort.by(Sort.Direction.DESC, "phoneNumber") // Java field name, not DB column14 );15
16 return userRepo.findByPhone(phone, pageable);17 // JPA automatically appends: ... LIMIT 5 OFFSET 0 for page 018 }19}Generated SQL (for page 0, size 5, sort DESC):
1SELECT * FROM user_details WHERE phone_number = ?2ORDER BY phone_number DESC3LIMIT 5 OFFSET 0countQuery parameter is required for native query pagination when returning Page. JPA needs a count query to calculate total pages. For List return types (no total count needed), countQuery is not required.7. Why Criteria API Exists The Gap
The Problem Statement
After learning JPQL and native queries, a natural question arises:
"Native query supports dynamic queries. JPQL has JPA management benefits. Why not just always use native queries for dynamic cases?"
The answer is that native queries sacrifice two critical JPA benefits:
| JPQL Benefit Lost in Native Query | Impact |
|---|---|
| DB independence | Changing database requires rewriting all native queries |
| Entity lifecycle management + L1 caching | No Persistence Context tracking, no automatic dirty checking |
The Criteria API fills this gap:
1JPQL: DB independent, JPA managed, but NO dynamic query support2Native Query: Dynamic queries supported, but DB dependent, no JPA management3Criteria API: DB independent + JPA managed + Dynamic query support ✅Type Safety Benefit
Native queries are strings — they compile even if you mistype a column name. Criteria API uses Java objects:
1// Native query — typo goes undetected until runtime2"SELECT * FROM user_detail WHERE user_nme = ?" // ← 'nme' typo compiles fine!3
4// Criteria API — type-safe Java objects5root.get("name") // If "name" field doesn't exist on entity → compile-time or startup error8. Criteria API Architecture & Hierarchy
Understanding the hierarchy is the key to making Criteria API easy. Every Criteria API query is built through this chain:
Component Roles
| Component | Role | Created By |
|---|---|---|
EntityManager | Entry point — provides getCriteriaBuilder() | Spring injection (@PersistenceContext) |
CriteriaBuilder | Factory — creates queries, predicates, expressions | entityManager.getCriteriaBuilder() |
CriteriaQuery | The query object — holds FROM, SELECT, WHERE, ORDER BY | criteriaBuilder.createQuery(T.class) |
Root | Represents the primary table (FROM clause) | criteriaQuery.from(T.class) |
Join | Represents a joined table | root.join(fieldName, JoinType) |
Predicate | A single WHERE condition or combination of conditions | criteriaBuilder.equal(), .like(), .and(), etc. |
TypedQuery | Executable query object with pagination support | entityManager.createQuery(criteriaQuery) |
9. Criteria API Step-by-Step: Select All Fields
Use Case: Fetch all `UserDetails` where phone matches a given number
1@Service2public class UserService {3
4 @PersistenceContext5 private EntityManager entityManager;6
7 public List<UserDetails> getUsersByPhone(String phoneNumber) {8
9 // ─── Step 1: Get CriteriaBuilder ───────────────────────────────10 CriteriaBuilder cb = entityManager.getCriteriaBuilder();11 // cb is the factory — we use it to create everything else12
13 // ─── Step 2: Create CriteriaQuery ──────────────────────────────14 // UserDetails.class tells JPA: each result row maps to a UserDetails object15 CriteriaQuery<UserDetails> cq = cb.createQuery(UserDetails.class);16
17 // ─── Step 3: Define FROM clause (Root = table 1) ───────────────18 Root<UserDetails> root = cq.from(UserDetails.class);19 // 'root' represents the user_details table20 // It is used to reference columns: root.get("fieldName")21
22 // ─── Step 4: Define SELECT clause ──────────────────────────────23 cq.select(root);24 // Equivalent to: SELECT * FROM user_details25 // (select all fields of the entity)26
27 // ─── Step 5: Build WHERE predicate ─────────────────────────────28 Predicate phonePredicate = cb.equal(29 root.get("phone"), // Entity field name (Java), not DB column name30 phoneNumber // Value to compare against31 );32
33 // ─── Step 6: Apply WHERE clause ────────────────────────────────34 cq.where(phonePredicate);35 // Equivalent to: WHERE phone = :phoneNumber36
37 // ─── Step 7: Create TypedQuery (executable) ────────────────────38 TypedQuery<UserDetails> typedQuery = entityManager.createQuery(cq);39
40 // ─── Step 8: Execute and return results ────────────────────────41 return typedQuery.getResultList();42 // Equivalent to: getResultList() → List<UserDetails>43 }44}Generated SQL:
1SELECT id, user_name, phone_number2FROM user_details3WHERE phone_number = ?Dynamic Version Only Add WHERE If Parameter Is Present
1public List<UserDetails> getUsersDynamic(String phoneNumber) {2 CriteriaBuilder cb = entityManager.getCriteriaBuilder();3 CriteriaQuery<UserDetails> cq = cb.createQuery(UserDetails.class);4 Root<UserDetails> root = cq.from(UserDetails.class);5 cq.select(root);6
7 // Build list of predicates dynamically8 List<Predicate> predicates = new ArrayList<>();9
10 if (phoneNumber != null && !phoneNumber.isEmpty()) {11 predicates.add(cb.equal(root.get("phone"), phoneNumber));12 }13 // Add more conditions here as needed...14
15 // Apply all collected predicates as AND conditions16 cq.where(cb.and(predicates.toArray(new Predicate[0])));17
18 return entityManager.createQuery(cq).getResultList();19}10. Criteria API Predicates (Where Conditions)
Predicates are the building blocks of WHERE clauses in Criteria API. The CriteriaBuilder provides methods to create all standard SQL conditions.
Comparison Operators
1// cb = CriteriaBuilder, root = Root<UserDetails>2
3// Equality: WHERE phone = '1234567890'4Predicate eq = cb.equal(root.get("phone"), "1234567890");5
6// Not equal: WHERE phone <> '1234567890'7Predicate neq = cb.notEqual(root.get("phone"), "1234567890");8
9// Greater than: WHERE id > 510Predicate gt = cb.greaterThan(root.get("id"), 5L);11
12// Greater than or equal: WHERE id >= 513Predicate gte = cb.greaterThanOrEqualTo(root.get("id"), 5L);14
15// Less than: WHERE id < 1016Predicate lt = cb.lessThan(root.get("id"), 10L);17
18// Less than or equal: WHERE id <= 1019Predicate lte = cb.lessThanOrEqualTo(root.get("id"), 10L);String Operations
1// LIKE: WHERE user_name LIKE '%Ali%'2Predicate like = cb.like(root.get("name"), "%Ali%");3
4// NOT LIKE: WHERE user_name NOT LIKE '%test%'5Predicate notLike = cb.notLike(root.get("name"), "%test%");Logical Operators Combining Predicates
1// Create two individual predicates2Predicate predPhone = cb.equal(root.get("phone"), "1234567890");3Predicate predName = cb.notEqual(root.get("name"), "AA");4
5// AND: WHERE phone = '1234567890' AND name <> 'AA'6Predicate andPred = cb.and(predPhone, predName);7
8// OR: WHERE phone = '1234567890' OR name <> 'AA'9Predicate orPred = cb.or(predPhone, predName);10
11// NOT: WHERE NOT (phone = '1234567890')12Predicate notPred = cb.not(predPhone);13
14// Apply to query15cq.where(andPred);Collection Operations (IN)
1// IN: WHERE phone IN ('111', '222', '333')2Predicate inPred = root.get("phone").in("111", "222", "333");3
4// NOT IN:5Predicate notInPred = cb.not(root.get("phone").in("111", "222", "333"));6
7// Apply8cq.where(inPred);Complete Predicate Reference Table
| SQL Operator | CriteriaBuilder Method |
|---|---|
= value | cb.equal(path, value) |
<> value | cb.notEqual(path, value) |
> value | cb.greaterThan(path, value) |
>= value | cb.greaterThanOrEqualTo(path, value) |
< value | cb.lessThan(path, value) |
<= value | cb.lessThanOrEqualTo(path, value) |
LIKE pattern | cb.like(path, pattern) |
NOT LIKE pattern | cb.notLike(path, pattern) |
AND | cb.and(pred1, pred2, ...) |
OR | cb.or(pred1, pred2, ...) |
NOT | cb.not(predicate) |
IN (...) | path.in(value1, value2, ...) |
NOT IN (...) | cb.not(path.in(...)) |
IS NULL | cb.isNull(path) |
IS NOT NULL | cb.isNotNull(path) |
BETWEEN a AND b | cb.between(path, a, b) |
11. Criteria API Selecting Specific Fields (Multi-Select)
When you want only specific columns (not all entity fields), use multiSelect and change the query type to Object[].
Use Case: Fetch only `name` and `phone` from `UserDetails`
1public List<UserDTO> getUserNameAndPhone(String phoneNumber) {2
3 CriteriaBuilder cb = entityManager.getCriteriaBuilder();4
5 // Step 1: Query type is Object[] because each row has mixed fields6 CriteriaQuery<Object[]> cq = cb.createQuery(Object[].class);7
8 // Step 2: FROM clause9 Root<UserDetails> root = cq.from(UserDetails.class);10
11 // Step 3: SELECT specific fields using multiSelect12 cq.multiSelect(13 root.get("name"), // First element of Object[] → String14 root.get("phone") // Second element of Object[] → String15 );16 // Equivalent to: SELECT user_name, phone_number FROM user_details17
18 // Step 4: WHERE clause19 Predicate phonePredicate = cb.equal(root.get("phone"), phoneNumber);20 cq.where(phonePredicate);21
22 // Step 5: Execute23 TypedQuery<Object[]> typedQuery = entityManager.createQuery(cq);24 List<Object[]> rawResults = typedQuery.getResultList();25
26 // Step 6: Map Object[] to DTO27 return rawResults.stream()28 .map(row -> new UserDTO(29 (String) row[0], // name30 (String) row[1] // phone31 ))32 .collect(Collectors.toList());33}Generated SQL:
1SELECT user_name, phone_number2FROM user_details3WHERE phone_number = ?multiSelect, JPA cannot map results to an entity automatically. You receive Object[] and must cast and map each element manually. The order of fields in multiSelect(...) matches the order in the Object[] array.12. Criteria API Joins
Use Case: Join `UserDetails` with `UserAddress` to fetch name and city
Joins in Criteria API use entity field names (not table names), because JPA navigates through entity relationships defined by @OneToOne, @OneToMany, etc.
1public List<Object[]> getUsersWithAddress() {2
3 CriteriaBuilder cb = entityManager.getCriteriaBuilder();4
5 // Each row has mixed types → Object[]6 CriteriaQuery<Object[]> cq = cb.createQuery(Object[].class);7
8 // Step 1: FROM — primary table (Root = Table 1)9 Root<UserDetails> userRoot = cq.from(UserDetails.class);10 // userRoot represents: FROM user_details11
12 // Step 2: JOIN — use the Java field name of the relationship13 // UserDetails has: @OneToOne UserAddress userAddress;14 // So we reference the field name "userAddress", not the table name15 Join<UserDetails, UserAddress> addressJoin = userRoot.join(16 "userAddress", // Field name in UserDetails entity17 JoinType.INNER // INNER JOIN (also: JoinType.LEFT, JoinType.RIGHT)18 );19 // Equivalent to: INNER JOIN user_address ON user_details.id = user_address.user_id20
21 // Step 3: SELECT specific fields from both tables22 cq.multiSelect(23 userRoot.get("name"), // From user_details table24 addressJoin.get("city") // From user_address table (via join)25 );26 // Equivalent to: SELECT u.user_name, a.city27
28 // Step 4: Optional WHERE clause29 // cq.where(cb.equal(addressJoin.get("city"), "Mumbai"));30
31 // Step 5: Execute32 TypedQuery<Object[]> typedQuery = entityManager.createQuery(cq);33 return typedQuery.getResultList();34}Generated SQL:
1SELECT u.user_name, a.city2FROM user_details u3INNER JOIN user_address a ON u.id = a.user_detail_idJoin Types
JoinType | SQL Equivalent | Behaviour |
|---|---|---|
JoinType.INNER | INNER JOIN | Only rows with matches in both tables |
JoinType.LEFT | LEFT OUTER JOIN | All rows from left table; NULL for non-matching right |
JoinType.RIGHT | RIGHT OUTER JOIN | All rows from right table; NULL for non-matching left |
root.join("fieldName", JoinType.X) must be the Java entity field name as defined in the entity class with @OneToOne, @OneToMany, @ManyToOne, or @ManyToMany annotations — not the database column name or table name.13. Criteria API Pagination and Sorting
Pagination with `TypedQuery`
Pagination in Criteria API is applied on the TypedQuery object (after the query is built):
1public List<UserDetails> getUsersPaged(String phone, int pageNumber, int pageSize) {2
3 CriteriaBuilder cb = entityManager.getCriteriaBuilder();4 CriteriaQuery<UserDetails> cq = cb.createQuery(UserDetails.class);5 Root<UserDetails> root = cq.from(UserDetails.class);6 cq.select(root);7
8 // WHERE clause9 if (phone != null) {10 cq.where(cb.equal(root.get("phone"), phone));11 }12
13 // Sorting — applied on CriteriaQuery via orderBy14 cq.orderBy(cb.desc(root.get("phone")));15 // Equivalent to: ORDER BY phone_number DESC16 // Use cb.asc() for ascending17
18 // Create TypedQuery19 TypedQuery<UserDetails> typedQuery = entityManager.createQuery(cq);20
21 // Pagination — applied on TypedQuery22 typedQuery.setFirstResult(pageNumber * pageSize); // OFFSET: records to skip23 typedQuery.setMaxResults(pageSize); // LIMIT: records per page24
25 return typedQuery.getResultList();26}Generated SQL (page 0, size 5, sort phone DESC):
1SELECT id, user_name, phone_number2FROM user_details3WHERE phone_number = ?4ORDER BY phone_number DESC5LIMIT 5 OFFSET 0Pagination Parameters Explained
| Method | SQL Equivalent | Calculation |
|---|---|---|
setFirstResult(n) | OFFSET n | pageNumber * pageSize (page 0 → offset 0, page 1 → offset 5 for size 5) |
setMaxResults(n) | LIMIT n | Page size (records per page) |
Multiple Sort Criteria
1// ORDER BY phone DESC, name ASC2cq.orderBy(3 cb.desc(root.get("phone")),4 cb.asc(root.get("name"))5);14. Comparison Table JPQL vs Native Query vs Criteria API
| Feature | JPQL | Native Query | Criteria API |
|---|---|---|---|
| Language | JPQL (entity-based) | Plain SQL | Java objects (type-safe) |
| Operates on | Entity classes | DB tables/columns | Entity classes |
| DB independent | ✅ | ❌ (DB specific) | ✅ |
| L1 Caching | ✅ | ❌ | ✅ |
| Entity lifecycle management | ✅ | ❌ | ✅ |
| Dynamic query building | ❌ | ✅ | ✅ |
| Type safety | Partial (strings) | ❌ (full strings) | ✅ (Java objects) |
| Complex DB features (JSONB, CTE) | ❌ | ✅ | ❌ |
| Unrelated entity joins | Difficult | ✅ | ❌ (needs relationship) |
| Pagination support | ✅ (via Pageable) | ✅ (manual or Pageable) | ✅ (via TypedQuery) |
| Sorting support | ✅ | ✅ | ✅ |
| Complexity | Low | Medium | Medium-High |
| Best for | Standard CRUD | Complex SQL, bulk ops | Dynamic JPA queries |
15. Common Mistakes & Best Practices
Common Mistakes
◆ Using Entity Names in Native Queries
1// WRONG — native query must use DB table/column names2@Query(value = "SELECT * FROM UserDetails WHERE name = :name", nativeQuery = true)3
4// CORRECT — use actual table and column names5@Query(value = "SELECT * FROM user_details WHERE user_name = :name", nativeQuery = true)◆ Forgetting `countQuery` for Native Paginated Queries
1// WRONG — will throw exception when using Page<T> return type2@Query(value = "SELECT * FROM user_details", nativeQuery = true)3Page<UserDetails> findAll(Pageable pageable);4
5// CORRECT6@Query(7 value = "SELECT * FROM user_details",8 countQuery = "SELECT COUNT(*) FROM user_details", // ← Required for Page<T>9 nativeQuery = true10)11Page<UserDetails> findAll(Pageable pageable);◆ SQL Injection via String Concatenation in Dynamic Queries
1// DANGEROUS — never do this2queryBuilder.append("AND user_name = '" + username + "'"); // SQL injection risk!3
4// SAFE — always use parameterized queries5queryBuilder.append("AND user_name = ? ");6parameters.add(username);◆ Using DB Column Names in Criteria API
1// WRONG — Criteria API uses Java entity field names2root.get("user_name") // DB column name — will fail!3
4// CORRECT — use Java field name as declared in the entity class5root.get("name") // Java field name in UserDetails◆ Not Using `@Transactional` When Required
1// WRONG — native queries that modify data need a transaction2public void updateUser(Long id, String name) {3 entityManager.createNativeQuery("UPDATE user_details SET user_name = ? WHERE id = ?")4 .setParameter(1, name)5 .setParameter(2, id)6 .executeUpdate(); // Throws TransactionRequiredException!7}8
9// CORRECT10@Transactional11public void updateUser(Long id, String name) {12 entityManager.createNativeQuery("UPDATE user_details SET user_name = ? WHERE id = ?")13 .setParameter(1, name)14 .setParameter(2, id)15 .executeUpdate();16}Best Practices
- Default to JPQL for standard operations — use native queries only when JPQL cannot express what you need.
- Default to Criteria API over native queries for dynamic query requirements — it gives JPA management benefits.
- Always use parameterized queries (
?withsetParameter) — never string-concatenate values into queries. - Validate sort field names against an allowlist before appending to SQL strings.
- Use DTOs for partial field projections — never return partial entity objects.
- Add
countQuerywhen using native queries withPagereturn type. - Keep Criteria API queries in the service layer (via
EntityManager) — they are too complex for repository interfaces. - Create helper methods for repeated predicates to avoid code duplication in Criteria API.
16. Interview Notes
Commonly Asked Questions
Q: What is a native query in JPA and when would you use it?
A native query is a plain SQL query executed directly against the database. Use it when JPQL is insufficient: for JSONB column queries, joins between unrelated entities, database-specific functions, or when raw SQL performance is required for bulk operations.
Q: What are the disadvantages of native queries?
Native queries are database-specific (not portable across DB changes), bypass JPA's first-level caching (no Persistence Context), and don't participate in JPA's entity lifecycle management. Any future DB migration requires rewriting all native queries.
Q: What is the WHERE 1=1 pattern and why is it used?
It is an always-true dummy condition that allows safely appendingAND conditionclauses dynamically without needing to track whether the WHERE keyword has been added yet. The database query planner eliminates1=1at zero cost.
Q: How do you return partial fields from a native query?
Two approaches: (1) Use@NamedNativeQuery+@SqlResultSetMappingwith@ConstructorResulton the entity class to automatically map results to a DTO. (2) ReturnListand manually cast and map each array element in service code.
Q: What is the Criteria API and why does it exist?
The Criteria API provides a type-safe, object-oriented way to build dynamic queries in JPA. It fills the gap between JPQL (managed by JPA, DB-independent, but no dynamic queries) and native queries (dynamic, but DB-dependent and unmanaged). Criteria API gives you dynamic query building while keeping JPA's entity management, caching, and DB independence.
Q: What are CriteriaBuilder, CriteriaQuery, Root, and TypedQuery? Explain their roles.
CriteriaBuilder: factory for creating all query components.CriteriaQuery: the query being built (holds FROM, SELECT, WHERE, ORDER BY).Root: represents the primary FROM table and is used to reference columns.TypedQuery: the executable query object that runs the built criteria query and supports pagination viasetFirstResult/setMaxResults.
Q: How do you add pagination and sorting to a Criteria API query?
Sorting is added viacriteriaQuery.orderBy(cb.desc(root.get("fieldName")))on theCriteriaQuery. Pagination is applied on theTypedQueryusingtypedQuery.setFirstResult(pageNumber * pageSize)for offset andtypedQuery.setMaxResults(pageSize)for limit.
Q: What is the difference between select and multiSelect in Criteria API?
cq.select(root)selects all fields of the entity (equivalent toSELECT *) and returns the full entity type.cq.multiSelect(root.get("field1"), root.get("field2"))selects specific fields and the result type must beObject[], which you then manually map.
Q: How do joins work in Criteria API?
Joins use entity relationship field names (not table names):root.join("fieldName", JoinType.INNER). The field must be annotated with@OneToOne,@OneToMany, etc. in the entity. JPA uses the relationship metadata to generate the correct JOIN condition automatically.
17. Practice Questions
Easy
- How do you enable native query mode in a
@Queryannotation? - What is the difference between using entity field names and DB column names in a native query?
- What does
WHERE 1=1accomplish in a dynamic query? - What method on
TypedQueryis equivalent to SQLLIMIT? - List three scenarios where a native query is preferred over JPQL.
Medium
- Write a native query repository method that returns only
nameandphonefields using@SqlResultSetMapping. - Write a dynamic native query method that filters by
usernameand/orphone(both optional) usingEntityManager.createNativeQuery(). - Write a Criteria API query that fetches
UserDetailswherephoneis in a given list andnameis not null. - Explain the full Criteria API hierarchy and the role of each component.
- Write a paginated, sorted Criteria API query for
UserDetailssorted byphonedescending, page size 10. - What happens if you omit
countQueryin a native query that returnsPage?
Hard
- Design a generic search service method that accepts any combination of
name,phone, andcity(via a join withUserAddress) as optional filters and returns paginatedUserDetails. Implement this using Criteria API with dynamic predicates. - Compare native query and Criteria API for a use case where you need to search users by 5 optional filters and return paginated results. Which would you choose and why? What are the trade-offs?
- Implement
@SqlResultSetMappingfor a native query that joinsuser_detailsanduser_addresstables and returns a DTO withname,phone, andcity. - A junior developer writes:
queryBuilder.append("ORDER BY " + userInputField + " DESC"). What is the security vulnerability and how do you fix it?
18. Summary
1NATIVE QUERIES — AT A GLANCE2─────────────────────────────────────────────────────────────────────────3
4WHEN TO USE:5 • Complex SQL (JSONB, CTEs, window functions, unrelated joins)6 • Bulk operations where speed > JPA management7 • Aggregations returning non-entity types (COUNT, SUM, AVG)8
9HOW TO USE:10 • @Query(value = "SQL", nativeQuery = true) — static queries11 • entityManager.createNativeQuery(string) — dynamic queries12 • Always use parameterized queries (?) — never string-concatenate values13
14PARTIAL FIELD MAPPING:15 • SELECT * → JPA maps automatically to entity16 • SELECT field1, field2 → must map manually:17 - Strategy 1: @NamedNativeQuery + @SqlResultSetMapping + @ConstructorResult18 - Strategy 2: Return List<Object[]> and map in service code19
20DYNAMIC NATIVE QUERIES:21 • StringBuilder + WHERE 1=1 pattern22 • List<Object> parameters → setParameter(index, value) (1-based)23 • Order: build string → create query → set params → execute → map results24
25PAGINATION (native):26 • Dynamic: append LIMIT ? OFFSET ? to string, add to params27 • @Query: add Pageable parameter + countQuery attribute28
29─────────────────────────────────────────────────────────────────────────30
31CRITERIA API — AT A GLANCE32─────────────────────────────────────────────────────────────────────────33
34WHY IT EXISTS:35 • JPQL = DB-independent, JPA-managed, but NO dynamic queries36 • Native = dynamic, but DB-dependent, NO JPA management37 • Criteria API = DB-independent + JPA-managed + dynamic ✅38
39HIERARCHY (always follow this order):40 1. EntityManager → getCriteriaBuilder() → CriteriaBuilder41 2. CriteriaBuilder → createQuery(T.class) → CriteriaQuery<T>42 3. CriteriaQuery → from(T.class) → Root<T>43 4. Root → join(field, JoinType) → Join<X,Y> (if needed)44 5. CriteriaBuilder → equal/like/gt/and/or... → Predicate45 6. CriteriaQuery → where(predicate)46 7. CriteriaQuery → orderBy(cb.desc/asc(root.get(field)))47 8. EntityManager → createQuery(criteriaQuery) → TypedQuery<T>48 9. TypedQuery → setFirstResult(offset) + setMaxResults(limit)49 10. TypedQuery → getResultList() → List<T>50
51SELECT:52 • All fields: cq.select(root) + CriteriaQuery<EntityClass>53 • Specific fields: cq.multiSelect(root.get("f1"), root.get("f2")) + CriteriaQuery<Object[]>54
55PREDICATES:56 • cb.equal, notEqual, gt, gte, lt, lte — comparison57 • cb.like, notLike — string matching58 • cb.and, or, not — logical combination59 • path.in(...), cb.not(path.in(...)) — collection membership60 • cb.isNull, isNotNull, between — null checks and range61
62PAGINATION:63 • typedQuery.setFirstResult(pageNum * pageSize) → OFFSET64 • typedQuery.setMaxResults(pageSize) → LIMITNext Up:
Spring Security — Authentication, Authorization, JWT, and Security Filters.
Mastery check
How well can you recall this?
Finished this lesson?