Use cases of methods of QueryByExampleExecutor<T> interface in Spring data JPA

inginia picture inginia · Oct 3, 2016 · Viewed 7.8k times · Source

What are the use cases of the methods of this interface QueryByExampleExecutor<T> in Spring data JPA. I have googled and found nothing more than the official documentation.

Perhaps someone can point me to the right resource with examples.

In particular, is findAll(Example<S> example, Pagable pageable) of that interface a simpler way to search, paginate, and sort?

Answer

Vladislav Kysliy picture Vladislav Kysliy · Dec 7, 2017

The Spring Data JPA query-by-example technique uses Examples and ExampleMatchers to convert entity instances into the underlying query. The current official documentation has several useful examples. Here is my example inspired by documentation:

Person.java

public class Person {

  @Id
  private String id;
  private String firstname;
  private String lastname;
  private Address address;

  // … getters and setters omitted
}

PersonResource.java:

@RestController
@RequestMapping("/api")
public class PersonResource {

@GetMapping("/persons/{name}")
@Timed
public ResponseEntity<List<Person>> getPersons(@ApiParam Pageable pageable, @PathVariable String  name) {
    log.debug("REST request to get Person by : {}", name);
    Person person = new Person();                         
    person.setFirstname(name);  
    Page<Person> page = personRepository.findAll(Example.of(person), pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/persons");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}