Filter entities in spring repository

2020-04-01 spring hibernate spring-boot spring-data-jpa spring-data

It is possible to apply a filter to results with annotations instead of extending method name?

For instance:

public interface JobRepository extends JpaRepository<Job, Long> {
    List<Job> findAllByUserAndEnabledIsTrue(User u);

Here I apply filter 'enabled == true'. But assume we have a lot of methods. Writing them with extended names is inconvenient. Could I apply this filter to whole repository?

I found @FilterDef but I don't know how to use and also if spring support this annotation.


As far as I know Spring Data JPA is not Hibernate dependent, and it can work with any JPA implementation. Hibernate's @Filters is not a JPA standard, so the simple answer is no! Spring JPA does not support @Filters.

But you can apply @Filters using AOP, and simply applying aspects on your repository methods.

By the way I believe the better solution is to have hand written queries using Spring Data JPA's @Query annotation. Because this way you can name methods after their context meaning, and not about their internal implementation.

For example you can name your method findActiveJobsForUser which could be more meaningful and readable.