Show Topics
Hide Topics

Spring Boot Custom Queries Example

 

JpaRepository

JpaRepository provides some JPA related method such as flushing the persistence context and delete record in a batch. JpaRepository extends PagingAndSortingRepository which in turn extends CrudRepository.

 

Their main functions are:

 

Because of the inheritance mentioned above, JpaRepository will have all the functions of CrudRepository and PagingAndSortingRepository.

 

 

Custom Queries

Spring Data JPA provides three different approaches for creating custom queries with query methods. Each of these approaches is described in following.

 

Using Method Name

  • Spring Data JPA has a built in query creation mechanism which can be used for parsing queries straight from the method name of a query method.
  • the method names of your repository interface are created by combining the property names of an entity object and the supported keywords.
     

 

JPA Named Queries

Spring Data JPA provides also support for the JPA Named Queries. You have got following alternatives for declaring the named queries:

  • You can use either named-query XML element or @NamedQuery annotation to create named queries with the JPA query language.
  • You can use either named-native-query XML element or @NamedNative query annotation to create queries with SQL if you are ready to tie your application with a specific database platform.

The only thing you have to do to use the created named queries is to name the query method of your repository interface to match with the name of your named query. See below Example code

 

The relevant part of my PersonRepository interface looks following

 

@Query Annotation

  • The @Queryannotation can be used to create queries by using the JPA query language and to bind these queries directly to the methods of your repository interface.
  • When the query method is called, Spring Data JPA will execute the query specified by the @Queryannotation
  • If there is a collision between the @Query annotation and the named queries, the query specified by using @Queryannotation will be executed

 

You may use positional parameters instead of named parameters in queries. Positional parameters are prefixed with a question mark (?) followed the numeric position of the parameter in the query. The Query.setParameter(integer position, Object value) method is used to set the parameter values.

 

 

Automatic Query Generation

The <jpa:repositories/> has an option query-lookup-strategy which defaults to “create-if-not-found” which will generate queries for us.The default is “create-if-not-found“. Other options are “create” or “use-declared-query“.

 

To create a find method that effectively does @Query(“FROM Product p where p.productId =:productId”)

 

 

 

Example

 

Student.java

 

 

StudentRepository.java

 

 

Application.java

 

 

Download Example