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

  1. Derived Query Methods: Methods that derive the query from the method name.
  2. @Query Annotation: Custom queries using JPQL or native SQL.
  3. Named Queries: Predefined queries that can be reused.
  4. Query Creation: Rules and conventions for creating query methods.

  1. 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.

  1. @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.

  1. 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 the Employee entity.
  • findByDepartment(@Param("department") String department): Uses the named query to find employees by department.

  1. 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

  1. Create a new method in the EmployeeRepository to find employees by their first name and order them by their last name in descending order.
  2. Create a custom query using the @Query annotation 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

Module 2: Spring Boot Basics

Module 3: Building RESTful Web Services

Module 4: Data Access with Spring Boot

Module 5: Spring Boot Security

Module 6: Testing in Spring Boot

Module 7: Advanced Spring Boot Features

Module 8: Deploying Spring Boot Applications

Module 9: Performance and Monitoring

Module 10: Best Practices and Tips

© Copyright 2024. All rights reserved