Custom Repository in Spring Data JPA
Spring Data JPA already provides many solutions that allow us querying data easier such as Query Method, Query Method, or four repository interface(JpaRepository
, PagingAndSortingRepository
, CrudRepository
, Repository
). These features are powerful, which help me a lot when building an application with Spring Data JPA. But a lot of time we still need to custom query or method to meet expectations or requirements.

The class design diagram above indicates how we can create a custom repository in Spring Data JPA. We just need to let EmployeeRepository implement the custom interface and define the implementation for the customized repository. Following this design, we can easy to apply query-by-example, the query-method as well as other Spring Data JPA features.
You might wonder where we put the @Repository
annotation. The answer is at EmployeeRepository
interface. We just have to provide the implementation of the customizing repository, other parts let Spring Framework complete. This article will not cover how this feature works under the hook. I only want to tell you that Spring Framework applies AOP and Proxy to build this powerful feature.
Custom Repository Code Example
We define a simple entity called Employee
And see how should we define the EmployeeRepository
interface.
Now we can see that EmployeeRepository
extends both EmployeeCustomizedRepository
and JpaRepository
we set EmployeeRepository
extends JpaRepository
to get all the powerful features of the built-in repository of Spring Data JPA.
Besides that we let EmployeeRepository
extends EmployeeCustomizedRepository
to make a custom repository.
EmployeeCustomizedRepository:
Take a look at the implementation of EmployeeCustomizedRepository
:
To simplify, I apply entityManage to make the custom method but you can implement it anyways to meets your expectations.
Test our work
I used CommandLineRunner to test our works, after running this program all matched records should be printed in the console log after UserCustomizedRepositoryImpl → implement
Conclusion
Up to now, we learned how we can design class, interface to able make a custom repository with Spring Data JPA. Belong that we have a code example to practice the theory.
Source demo: https://github.com/Programming-Sharing/spring-data-jpa-demo/tree/customizing-repository-spring-data-jpa
Give me motivation
To get new article update please follow our publication or follow us on social
Facebook: https://www.facebook.com/programmingsharing
Twitter: http://twitter.com/progsharing