Spring Data - Query By Example API
Introduction
Query by Example is a way in Spring that allows for dynamic query creation without writing any code or queries.
Note: In order to use Spring QBE feature, repository class need to be extended from QueryByExampleExecutor interface apart from extending from CrudRepository.
public interface EmployeeRepository extends CrudRepository<Employee, Integer>, QueryByExampleExecutor<Employee> {
...
}
Query by Example API
The API mainly gives the following:
a) Example: Example takes a data object (usually the entity object or a subtype of it) and a specification how to match properties
b) Example Matcher: The ExampleMatcher carries details on how to match particular fields. It can be reused across multiple Examples.
Example
Imagine we have an Employee class which has id, name & position field & in order to search all the employees whose position contains the word “Developer” then
@RequestMapping(value = "/emp/get", method = RequestMethod.GET)
public ResponseEntity<List<Employee>> EmpgetDetails(
@RequestParam(value="id") int empId,
@RequestParam(value="name") String empName,
@RequestParam(value="position") String position)
{
Employee emp = new Employee();
emp.setPosition(position);
Example<Employee> example = Example.of(emp);
List<Employee> ret_list = empRepository.findAll(example);
return new ResponseEntity<List<Employee>>(ret_list, HttpStatus.OK);
}