Spring Data JPA already provides many solutions that allow us querying data easier such as Query Method, Query Method, or four repository interface(
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
Now we can see that
EmployeeRepository extends both
JpaRepository we set
JpaRepository to get all the powerful features of the built-in repository of Spring Data JPA.
Besides that we let
EmployeeCustomizedRepository to make a custom repository.
Take a look at the implementation of
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
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.
Give me motivation
To get new article update please follow our publication or follow us on social