In this section, we will explore how to create and use query methods in Spring Data JPA. Query methods are a powerful feature that allows you to define database queries directly in your repository interfaces using method names.
Key Concepts
- Derived Query Methods: Methods that derive the query from the method name.
 - @Query Annotation: Custom queries using JPQL or native SQL.
 - Named Queries: Predefined queries that can be reused.
 - Query Creation: Rules and conventions for creating query methods.
 
- Derived Query Methods
 
Derived query methods are built by parsing the method name and generating the query based on the method name's structure.
Example
Let's assume we have an Employee entity:
@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String lastName;
    private String email;
    private String department;
    // Getters and Setters
}Repository Interface
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    List<Employee> findByLastName(String lastName);
    Employee findByEmail(String email);
    List<Employee> findByDepartmentAndLastName(String department, String lastName);
}Explanation
findByLastName(String lastName): Finds all employees with the given last name.findByEmail(String email): Finds an employee with the given email.findByDepartmentAndLastName(String department, String lastName): Finds employees with the given department and last name.
- @Query Annotation
 
The @Query annotation allows you to define custom queries using JPQL or native SQL.
Example
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    @Query("SELECT e FROM Employee e WHERE e.email = ?1")
    Employee findByEmailAddress(String email);
    @Query(value = "SELECT * FROM Employee e WHERE e.department = ?1", nativeQuery = true)
    List<Employee> findByDepartmentNative(String department);
}Explanation
@Query("SELECT e FROM Employee e WHERE e.email = ?1"): JPQL query to find an employee by email.@Query(value = "SELECT * FROM Employee e WHERE e.department = ?1", nativeQuery = true): Native SQL query to find employees by department.
- Named Queries
 
Named queries are defined in the entity class and can be reused in the repository.
Example
@Entity
@NamedQuery(name = "Employee.findByDepartment", query = "SELECT e FROM Employee e WHERE e.department = :department")
public class Employee {
    // Fields, getters, and setters
}Repository Interface
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    List<Employee> findByDepartment(@Param("department") String department);
}Explanation
@NamedQuery: Defines a named query in theEmployeeentity.findByDepartment(@Param("department") String department): Uses the named query to find employees by department.
- Query Creation
 
Spring Data JPA follows a set of conventions for creating query methods. Here are some common keywords:
| Keyword | Sample Method Name | JPQL Snippet | 
|---|---|---|
And | 
findByFirstNameAndLastName | 
... where x.firstName = ?1 and x.lastName = ?2 | 
Or | 
findByFirstNameOrLastName | 
... where x.firstName = ?1 or x.lastName = ?2 | 
Between | 
findByStartDateBetween | 
... where x.startDate between ?1 and ?2 | 
LessThan | 
findByAgeLessThan | 
... where x.age < ?1 | 
GreaterThan | 
findByAgeGreaterThan | 
... where x.age > ?1 | 
Like | 
findByFirstNameLike | 
... where x.firstName like ?1 | 
OrderBy | 
findByLastNameOrderByFirstNameAsc | 
... order by x.firstName asc | 
Practical Exercise
Task
- Create a new method in the 
EmployeeRepositoryto find employees by their first name and order them by their last name in descending order. - Create a custom query using the 
@Queryannotation to find employees whose email contains a specific domain. 
Solution
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    // Derived query method
    List<Employee> findByFirstNameOrderByLastNameDesc(String firstName);
    // Custom query using @Query annotation
    @Query("SELECT e FROM Employee e WHERE e.email LIKE %?1%")
    List<Employee> findByEmailDomain(String domain);
}Explanation
findByFirstNameOrderByLastNameDesc(String firstName): Finds employees by first name and orders them by last name in descending order.@Query("SELECT e FROM Employee e WHERE e.email LIKE %?1%"): Custom query to find employees whose email contains the specified domain.
Conclusion
In this section, we covered the basics of query methods in Spring Data JPA, including derived query methods, the @Query annotation, and named queries. We also provided practical examples and exercises to help you understand how to create and use query methods effectively. In the next module, we will delve into Spring Boot Security, starting with an introduction to Spring Security.
Spring Boot Course
Module 1: Introduction to Spring Boot
- What is Spring Boot?
 - Setting Up Your Development Environment
 - Creating Your First Spring Boot Application
 - Understanding Spring Boot Project Structure
 
Module 2: Spring Boot Basics
- Spring Boot Annotations
 - Dependency Injection in Spring Boot
 - Spring Boot Configuration
 - Spring Boot Properties
 
Module 3: Building RESTful Web Services
- Introduction to RESTful Web Services
 - Creating REST Controllers
 - Handling HTTP Methods
 - Exception Handling in REST
 
Module 4: Data Access with Spring Boot
- Introduction to Spring Data JPA
 - Configuring Data Sources
 - Creating JPA Entities
 - Using Spring Data Repositories
 - Query Methods in Spring Data JPA
 
Module 5: Spring Boot Security
- Introduction to Spring Security
 - Configuring Spring Security
 - User Authentication and Authorization
 - Implementing JWT Authentication
 
Module 6: Testing in Spring Boot
Module 7: Advanced Spring Boot Features
Module 8: Deploying Spring Boot Applications
Module 9: Performance and Monitoring
- Performance Tuning
 - Monitoring with Spring Boot Actuator
 - Using Prometheus and Grafana
 - Logging and Log Management
 
