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?
From the Spring Docs for Example
:
Support for query by example (QBE). An Example takes a probe to define the example. Matching options and type safety can be tuned using ExampleMatcher.
So this class and the QueryByExampleExecutor
interface are part of Spring Data's implementation of this Query By Example paradigm.
From the Wikipedia post on Query by Example :
Query by Example (QBE) is a database query language for relational databases. It was devised by Moshé M. Zloof at IBM Research during the mid-1970s, in parallel to the development of SQL. It is the first graphical query language, using visual tables where the user would enter commands, example elements and conditions.
Finally, the documentation for the #findAll
method that you reference states the following:
<S extends T> Page<S> findAll(Example<S> example, Pageable pageable)
Returns aPage
of entities matching the givenExample
. In case no match could be found, an emptyPage
is returned.
So essentially QBE represents a way of querying a relational DB using a more natural, template-based querying syntax, as opposed to using SQL, and Spring Data has an API which supports that.
The Spring Data JPA query-by-example technique uses Example
s and ExampleMatcher
s 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.