Adding Hibernate Entity Level Filtering feature to Spring Data JPA Repository

Baby Steps to Pro
2 min readDec 9, 2021

--

Those who have used data filtering features of hibernate should know that it is very powerful. You could define a set of filtering criteria to an entity class or a collection. Spring data JPA is a very handy library but it does not have fitering features. In this post, I will demonstrate how to add the hibernate filter features at entity level. We can just use annotation in your repositoy interface to enable this features.

Step 1. Define filter at entity level as usual. Just use hibernate @FilterDef annotation.

Step2. Define two custom annotations.

These two annotations are to be used in your repository interfaces. You could apply the hibernate filter defined in step 1 to specific query through these annotations.

Step3. Add a method to your Spring data JPA base repository.

This method will read the annotation you defined (i.e. @FilterQuery) and apply hibernate filter to the query by just simply unwrap the EntityManager. You could specify the parameter in your hibernate filter and also the parameter in you query in this method.

If you do not know how to add custom method to your Spring data JPA base repository, please see my previous post for how to customize your Spring data JPA base repository for detail. You can see in previous post that I intentionally expose the repository interface (i.e. the springDataRepositoryInterface property) in the GenericRepositoryImpl. This small tricks enable me to access the annotation in the repository interface easily.

Usage example:

In your repository, define which query you would like to apply hibernate filter through your @EntityFilter and @FilterQuery annotation.

In your service or business class that inject your repository, you could just simply call the doQueryWithFilter() method to enable the filtering function.

Originally published at https://www.borislam.com on December 9, 2021.

--

--

Baby Steps to Pro

We are technology enthusiasts with more than 15 years of software development experience. Our current focus is framework development and architectural design.