Additional filter of entity in Spring data based on profile

823 views Asked by At

I have a DB table, let's call it USERS. In this table, I have standard fields like name, surname, age, etc. This table is mapped to the JPA entity class:

@Entity
@Table(name = "users")
public class User {
    @Id
    @Column(name = "login")
    private String id;

    @Column(name = "name")
    private String name;
    //etc...
}

Now I need to have the possibility to filter some of the users based on the environment. The environment can be defined based on the Spring active profile. My assumption was to add the new DB column, let's say boolean filter, and based on the Spring profile to filter or not the user out.

The question is about the best way of implementation of this functionality so it would be clean and maintainable. One way is to have two different @Repository and based on the profile init the right one. One repository will return all the users but the other one will return only the users with filter=false.

What I don't like about this implementation is that there will be a lot of code duplication. For each repository method, I will have to have the same method in the second repository, but with the filtering based on one column. Is there a way do define maybe some kind of `interceptor`` that will do it automatically for each read query on the given DB entity?

1

There are 1 answers

3
Nobody On

Not interceptor, but one can do it using jpa criteria: docs

This way you can dynamically configure what you want. Afaik, in runtime it would be a bit slower than plain old solution with several @Repository marked with @ConditionalOnProperty, or other bit of configuration of your choice, however, it meets your requirement of changing behavior without the need of introducing several repos. What you would want to do is declare Specification /default one and pass it around. This way you could later on also configure your search in runtime too.