Search code examples
javaspringspring-bootjparepository

Spring Boot Repository working with optional Properties


I try to find out "if there is any entity with the given properties".

Given is the following sample entity:

@Entity
public class Foo {
    @Id
    private Long someId;
    @Column
    private String propA;
    @Column
    private String propB;
    @Column
    private String propC;
}

I try to find an entity with a given propA. Or propB. Or C. Or a combination of them. I know, I can do this with a JpaRepository, but I will get an exploding number of functions to write:

public interface FooRepository extends CrudRepository<Foo, Long> {

    boolean existsByPropA(String propA);
    boolean existsByPropB(String propB);
    boolean existsByPropC(String propC);
    boolean existsByPropAAndAndPropB(String propA, String propB);
    boolean existsByPropAAndPropC(String propA, String propC);
    // and much more to be written to get all combinations
}

Writing all possible combination is nonsense especially if new properties are to be added.

I am looking for a generic solution to this problem, or at least a keyword to search for as I am not yet very firm with JPA/Hibernate.

Thank you.


Solution

  • As a simple way, you can just use a query like this :

        @Query("SELECT t FROM Task  as t WHERE EXISTS (SELECT t.title FROM t WHERE t.title=:a or t.title=:b or t.title=:c or(t.title=:a and t.title=:b))")
        Boolean check(String a,String b,String c);
    

    but I think the best way is to use specifications