Search code examples
javaspringspring-datasingle-page-applicationspring-data-jdbc

Spring Repository query by multi-valued property


Trying to solve a problem where I have a class Student.

public class Student {
    @Id
    UUID id;
    String name;
    Long year;
    List<Attribute> attributes;
}

And a class Attribute

public class Attribute {
    @Id
    private UUID id;
    private String field;
    private String value;
}

Now I wanna search by year and by a list of attributes.

public interface StudentRepository extends PagingAndSortingRepository<Student, UUID> {
    Page<Student> findStudentByYearAndAttributesIn(Long year, List<Attribute> attributes, Pageable pageable);
}

A possible search would be to look for all the students from the year 2000 who had brown or blond hair or brown or blue eyes.

{
  "hair" : ["brown","blonde"],
  "eyes" : ["brown","blue"]
}

When I try to run this project I get an error

Error creating bean with name 'studentRepository' defined in com.example.StudentRepository defined in @EnableJdbcRepositories declared on Application: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Cannot query by multi-valued property: attributes; nested exception is java.lang.IllegalArgumentException: Cannot query by multi-valued property: attributes

How can I query for this multi-valued properties?


Solution

  • You'll have to define a custom query in a @Query annotation.