spring-bootspring-data-jpaquery-by-example

Spring Jpa Query by Example collection


Let's say I have an entity

public class Person {
    private String id;
    private String firstname;
    private String lastname;
    private Set<Car> ownedCars;
}

Is there a way I can use query by example to find any person named James having both a Ferrari and Lamborghini?

If I use:

Person p = new Person();
p.setName("James");
p.getOwnedCars.addCar(new Car("Lamborgnihi"));
p.getOwnedCars.addCar(new Car("Ferrari"));
Example<Person> exampleOfPerson = Example.of(p);
List<Person> foundPersons = personRepository.finaAll(exampleOfPerson);

it seems it queries only on person's attributes and ignores any child collections.


Solution

  • You can use a query method for that. Let's say your Car has a property name that can be "Lamborghini" or "Ferrari"

    interface PersonRepository extends JpaRepository<Person, String> {
      List<Person> findByOwnedCarsNameIn(Collection<String> names);
    }
    

    Then you use it like this:

    personRepository.findByOwnedCarsNameIn(Arrays.asList("Ferrari","Lamborghini"));
    

    Some gotchas:

    The method parameter can take any subclass of Collection, or an array.

    The property names on Person and Car must match the method signature and the parameter name as shown above for spring to know how to generate the query, i.e. Person must have a property called "cars", and Car must have a property called "name".

    I used JpaRepository, but this works with any of the Repository interfaces provided with spring data JPA