0% found this document useful (0 votes)
4 views

Spring_Data_JPA_Full_Guide

The document outlines various derived query techniques in Spring Data JPA, including comparison operators, string matching, date-based queries, and relationship-based queries. It also covers the use of subqueries, different types of joins, and fetch joins for performance optimization. Mastering these techniques allows for the creation of optimized and complex queries in applications.

Uploaded by

Vpn Account
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Spring_Data_JPA_Full_Guide

The document outlines various derived query techniques in Spring Data JPA, including comparison operators, string matching, date-based queries, and relationship-based queries. It also covers the use of subqueries, different types of joins, and fetch joins for performance optimization. Mastering these techniques allows for the creation of optimized and complex queries in applications.

Uploaded by

Vpn Account
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

# 1.

Basic Spring Data JPA Derived Queries

Spring Data JPA provides a rich set of derived query keywords that translate into SQL queries.

## **Comparison Operators**

| **Spring Data JPA Keyword** | **SQL Equivalent** | **Example Query Method** | **Generated
SQL** |
|----------------------|----------------|----------------------|----------------------|
| After | `>` (for dates) | `findByCreatedAtAfter(LocalDate date)` | `SELECT * FROM user WHERE
created_at > ?` |
| Before | `<` (for dates) | `findByCreatedAtBefore(LocalDate date)` | `SELECT * FROM user
WHERE created_at < ?` |
| IsGreaterThan | `>` | `findBySalaryIsGreaterThan(Double salary)` | `SELECT * FROM user
WHERE salary > ?` |
| IsLessThan | `<` | `findBySalaryIsLessThan(Double salary)` | `SELECT * FROM user WHERE
salary < ?` |

---

# 2. String Matching and Boolean Queries

| **Spring Data JPA Keyword** | **SQL Equivalent** | **Example Query Method** | **Generated
SQL** |
|----------------------|----------------|----------------------|----------------------|
| Contains | `LIKE %value%` | `findByNameContaining(String name)` | `SELECT * FROM user
WHERE name LIKE %?%` |
| NotContains | `NOT LIKE %value%` | `findByNameNotContaining(String name)` | `SELECT *
FROM user WHERE name NOT LIKE %?%` |
| StartsWith | `LIKE value%` | `findByNameStartingWith(String prefix)` | `SELECT * FROM user
WHERE name LIKE ?%` |
| EndsWith | `LIKE %value` | `findByNameEndingWith(String suffix)` | `SELECT * FROM user
WHERE name LIKE %?` |
| IsTrue | `= TRUE` | `findByActiveIsTrue()` | `SELECT * FROM user WHERE active = TRUE` |
| IsFalse | `= FALSE` | `findByActiveIsFalse()` | `SELECT * FROM user WHERE active = FALSE` |

---
# 3. Date-Based Queries

| **Spring Data JPA Keyword** | **SQL Equivalent** | **Example Query Method** | **Generated
SQL** |
|----------------------|----------------|----------------------|----------------------|
| After | `>` | `findByCreatedAtAfter(LocalDateTime date)` | `SELECT * FROM user WHERE
created_at > ?` |
| Before | `<` | `findByCreatedAtBefore(LocalDateTime date)` | `SELECT * FROM user WHERE
created_at < ?` |
| Between | `BETWEEN` | `findByCreatedAtBetween(LocalDate start, LocalDate end)` | `SELECT *
FROM user WHERE created_at BETWEEN ? AND ?` |
| Year | `YEAR(column) = ?` | `findByCreatedAtYear(int year)` | `SELECT * FROM user WHERE
YEAR(created_at) = ?` |
| Month | `MONTH(column) = ?` | `findByCreatedAtMonth(int month)` | `SELECT * FROM user
WHERE MONTH(created_at) = ?` |
| Day | `DAY(column) = ?` | `findByCreatedAtDay(int day)` | `SELECT * FROM user WHERE
DAY(created_at) = ?` |

---

# 4. Queries on Entity Relationships

Spring Data JPA supports queries on relationships like OneToMany and ManyToOne.

## Example Query to Find Users with a Specific Order Status


```java
List<User> findByOrdersStatus(String status);
```
**Generated SQL:**
```sql
SELECT * FROM user u
INNER JOIN orders o ON u.id = o.user_id
WHERE o.status = ?;
```

---
# 5. Subqueries in Spring Data JPA

For complex conditions, use @Query with Subqueries.

## Example: Find Users Who Placed More Than 5 Orders


```java
@Query("SELECT u FROM User u WHERE (SELECT COUNT(o) FROM Order o WHERE o.user =
u) > 5")
List<User> findUsersWithMoreThanFiveOrders();
```
**Generated SQL:**
```sql
SELECT * FROM user u
WHERE (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) > 5;
```

---

# 6. Joins in Spring Data JPA Queries

Spring Data JPA allows different types of joins to fetch related entities.

## INNER JOIN
```java
@Query("SELECT o FROM Order o INNER JOIN o.user u WHERE u.name = :name")
List<Order> findOrdersByUserName(@Param("name") String name);
```
**Generated SQL:**
```sql
SELECT o.* FROM orders o
INNER JOIN user u ON o.user_id = u.id
WHERE u.name = ?;
```

## LEFT JOIN
```java
@Query("SELECT u FROM User u LEFT JOIN FETCH u.orders")
List<User> findAllUsersWithOrders();
```
**Generated SQL:**
```sql
SELECT u.*, o.* FROM user u
LEFT JOIN orders o ON u.id = o.user_id;
```

---

# 7. Fetch Joins for Performance Optimization

To solve N+1 query problems, use JOIN FETCH.

## Example: Fetch Users and Their Orders in One Query


```java
@Query("SELECT u FROM User u JOIN FETCH u.orders WHERE u.name = :name")
List<User> findUsersWithOrders(@Param("name") String name);
```
**Generated SQL:**
```sql
SELECT u.*, o.* FROM user u
INNER JOIN orders o ON u.id = o.user_id
WHERE u.name = ?;
```

---

# **Summary**

### **1. Date-Based Queries**


- `After`, `Before`, `Between`, `Year`, `Month`, `Day`

### **2. Relationship-Based Queries**


- `OneToMany`, `ManyToOne`, `ManyToMany` with `JOIN` operations

### **3. Subqueries**


- **Find users with more than X orders**
### **4. Joins**
- `INNER JOIN` -> Only matching records
- `LEFT JOIN` -> All records from left table + matches from right
- `RIGHT JOIN` -> All records from right table + matches from left
- `CROSS JOIN` -> All possible combinations

### **5. Fetch Joins for Optimization**


- Solves **N+1 Query Problem** by fetching related entities in one query.

By mastering these **Spring Data JPA derived query techniques**, you can build **highly
optimized** and **complex** queries effortlessly!

You might also like