Hibernate’s @Filter Annotation

Yusuf BEŞTAŞ
2 min readJun 16, 2021

--

In this tutorial, I will explain how to use Filter annotation. Suppose we have an e-commerce website and we wanna filter shoes by their size. Such first of all we should create a “SHOES” entity and let’s check the example.

Above all let’s explain annotation which we don't know.

@FilterDef: Through this annotation. We define the name and parameters of the filter.

@Filters: Many filters are written to use.

@Filter: Adds a filter to an entity or a target entity.

, To use these annotations we must import the following packages.

import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.Filters;

As you may see in line 22 above, we defined 2 parameters in the @FilterDef. After that, we defined a filter as a “shoesFilter” and have a condition inside this. It means thatshoesSize should be between minShoeSize and maxShoeSize. Let’s use this filter.

As you may see inline 34above, we enabled the filter, and inside it, we named the filter we created and we added the parameters.

İnside Shoes table we have 3 data. Let’s run code.

As you may see we filtered their data too easily. These features give us a more flexible approach. At a runtime of the application, we may enable this filter and use the necessary parameters in certain cases. Which saves us a more dynamic approach.

Take care until the next post.

Yusuf BEŞTAŞ

--

--