...

/

Building Queries With Spring Data JPA

Building Queries With Spring Data JPA

Learn to build complex queries using Spring Data JPA.

We have learned how we can configure Spring Data JPA to implement a simple CRUD application. Now, it’s time to learn some advanced skills that will help us to implement real-life applications. In this chapter, we will cover:

  • How to write a custom query in addition to basic CRUD operation.

In the course of this chapter, we will extend our Elite Club application by adding a search functionality

Building queries

There are three methods we can use to build queries:

  • Query Methods
  • JPA Criteria API
  • Querydsl

Note: The scope of this course is limited to the Query Methods.

Query method

The simplest way to create queries with Spring Data JPA is to use query methods. Query methods are methods that are declared in the repository interface. Three techniques can be used to create a query method.

  • Query generation from method name
  • Named Queries
  • @Query annotation

Query generation from method name

Query generation from method name is a strategy where the executed query is generated from the name of a method in the repository interface. The naming convention, which is used to create the names of the query method, has 3 important parts.

  1. Method prefixes
  2. Property expressions
  3. Conditions

Method syntax to generate query goes like this [MethodPrefixes][PropertyExpression][Conditions].

Method prefixes

In order to ensure that method is identified as a query method, it must have predefined prefixes. The supported prefixes ...