4

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.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Matúš Zábojník
  • 1,084
  • 1
  • 10
  • 20

1 Answers1

2

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

SrThompson
  • 5,568
  • 2
  • 17
  • 25
  • the "NameIn(Collection names)" will return any person having either of the two cars listed. Is it possible to return only persons having both cars? Or do i have to query for persons with owned cars in collection and then check on such resultset which person is having both? – Matúš Zábojník May 02 '18 at 07:44
  • 2
    That's right, you would have to either do this query and filter the result set in java or build your own query with the values of the car names collection, since neither Spring Data nor SQL have a "find something that matches every value in this list exactly" native construct, the query would need to be more complex than what spring data repositories can generate automagically – SrThompson May 02 '18 at 14:54