Using Spring Data JPA can I do a query by example where a particular entity instance is used as the search criteria?
For example (no pun intended), if I have a Person
entity that looks like:
@Entity
public class Person {
private String firstName;
private String lastName;
private boolean employed;
private LocalDate dob;
...
}
I could find all employed persons with a last name of Smith born on January 1, 1977 with an example:
Person example = new Person();
example.setEmployed(true);
example.setLastName("Smith");
example.setDob(LocalDate.of(1977, Month.JANUARY, 1));
List<Person> foundPersons = personRepository.findByExample(example);
Spring data relies on top of JPA and EntityManager, not Hibernate and Session, and as such you do not have findByExample out of the box. You can use the spring data automatic query creation and write a method in your repository with the following signature:
This is now possible with Spring Data. Check out http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example
Note that this requires very recent 2016 versions
see https://github.com/paulvi/com.example.spring.findbyexample
Using Spring data's
Specification
interface I was able to approximate the use of query by example. Here's aPersonSpec
class which implementsSpecification
and requires an "example" person in order to setup thePredicate
returned by theSpecification
:The repository is simply:
Usage example: