Custom Query Methods in Spring Data JPA with Real Examples

One of the most powerful features of Spring Data JPA is its ability to generate SQL queries automatically from method names.


Instead of writing SQL manually, developers can create repository methods following specific naming conventions and Spring Data JPA automatically generates the required query.


What are Query Methods?

Query Methods are repository methods whose names describe the query that should be executed.

Spring Data JPA analyses the method name and generates the SQL query automatically.


Why Use Query Methods?

  • Less boilerplate code
  • No SQL required for simple queries
  • Improved readability
  • Faster development
  • Better maintainability

Employee Entity


@Entity
public class Employee {

    @Id
    @GeneratedValue(
        strategy =
        GenerationType.IDENTITY
    )
    private Long id;

    private String name;

    private String department;

    private Double salary;

}

Repository Layer


@Repository
public interface EmployeeRepository
extends JpaRepository<
        Employee,
        Long> {

}

Find By Name

Retrieve employees by name.



List<Employee>
findByName(String name);

Generated Query Conceptually:



SELECT *
FROM employees
WHERE name = ?

Find By Department


List<Employee>
findByDepartment(
    String department
);

Generated Query:



SELECT *
FROM employees
WHERE department = ?

Find By Salary Greater Than


List<Employee>
findBySalaryGreaterThan(
    Double salary
);

Returns employees with salaries higher than the specified amount.



SELECT *
FROM employees
WHERE salary > ?

Find By Salary Less Than


List<Employee>
findBySalaryLessThan(
    Double salary
);

Returns employees whose salary is below the specified value.


Find By Department And Salary

Multiple conditions can be combined.



List<Employee>
findByDepartmentAndSalaryGreaterThan(
    String department,
    Double salary
);

Generated Query:



SELECT *
FROM employees
WHERE department = ?
AND salary > ?

Find By Name Containing

Useful for search functionality.



List<Employee>
findByNameContaining(
    String keyword
);

Generated Query:



SELECT *
FROM employees
WHERE name LIKE '%keyword%'

Find By Name Starting With


List<Employee>
findByNameStartingWith(
    String prefix
);

Example:



findByNameStartingWith("Jo")

Matches:



John

Joseph

Jordan

Find By Name Ending With


List<Employee>
findByNameEndingWith(
    String suffix
);

Find Top Records

Spring Data JPA supports limiting results.



List<Employee>
findTop5ByOrderBySalaryDesc();

Returns the top five highest-paid employees.


Find First Record


Employee
findFirstByOrderBySalaryDesc();

Returns the highest-paid employee.


Find By Multiple Fields


List<Employee>
findByNameAndDepartment(
    String name,
    String department
);

Find By In Clause


List<Employee>
findByDepartmentIn(
    List<String>
    departments
);

Example:



IT

HR

Finance

Ignore Case Searches


List<Employee>
findByNameIgnoreCase(
    String name
);

Useful for user-friendly searches.


Combining Query Methods with Pagination


Page<Employee>
findByDepartment(

    String department,

    Pageable pageable

);

Results can be paginated while still using query methods.


Service Layer Example


public List<Employee>
getITEmployees() {

    return repository
            .findByDepartment(
                "IT"
            );

}

Controller Example


@GetMapping("/department")

public List<Employee>
getEmployeesByDepartment(

@RequestParam String department

) {

    return repository
            .findByDepartment(
                department
            );

}

Common Interview Questions

What are Query Methods in Spring Data JPA?

Methods whose names are automatically converted into SQL queries by Spring Data JPA.


Can query methods contain multiple conditions?

Yes. Conditions can be combined using And and Or.


Can pagination be used with query methods?

Yes. Query methods can accept Pageable parameters.


Can sorting be combined with query methods?

Yes. Spring Data JPA supports sorting and pagination together.


What happens if a method name becomes too long?

It may be better to use JPQL or @Query annotations.


Best Practices

  • Keep query method names readable.
  • Use query methods for simple queries.
  • Use JPQL for complex business queries.
  • Combine pagination whenever possible.
  • Avoid excessively long method names.

Frequently Asked Questions (FAQ)

Do query methods require SQL knowledge?

No. Spring Data JPA generates the queries automatically.


Can query methods join multiple tables?

For simple use cases yes. Complex joins often require JPQL or native queries.


Are query methods production ready?

Yes. They are widely used in enterprise Spring Boot applications.


Conclusion

Custom Query Methods are one of the most productive features of Spring Data JPA. They reduce boilerplate code and allow developers to create powerful database queries using simple method naming conventions. Understanding query methods is essential for Spring Boot development and interview preparation.


Keywords

Spring Data JPA Query Methods, Custom Query Methods, Spring Boot Repository Queries, findBy Example, JpaRepository Query Methods, Spring JPA Tutorial, Spring Data JPA Interview Questions, Repository Methods, Database Queries Spring Boot, Derived Query Methods, Spring Boot CRUD, Java Backend Development, Spring Framework Tutorial, JPA Methods, Spring Boot Database Access



Custom Query Methods in Spring Data JPA with Real Examples Custom Query Methods in Spring Data JPA with Real Examples Reviewed by 13thGhost on 3:25 AM Rating: 5

No comments:

Recommended Posts

Powered by Blogger.