Java Spring Boot REST Application Part 2: Queries

In the first part we created a simple REST application to provide access to our employees data. But in most of the cases you also need to query the data. Spring Data Repositories provide a simple way to do so. Let’s take the employees repository interface we’ve created and add an additional method for searching employees by their last name.

package at.grisa.example.rest_example;

import java.util.List;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Long> {
 List<Employee> findByLastNameIgnoreCase(@Param("lastName") String lastName);
}

Spring Data automatically recognizes the method findByLastNameIgnoreCase as a query by parsing the method name.

When we now start our spring REST application and send a HTTP GET request to http://localhost:8080/employees/search we will see the new query method as a new REST interface.

{
 "_links": {
 "findByLastNameIgnoreCase": {
 "href": "http://localhost:8080/employees/search/findByLastNameIgnoreCase{?lastName}",
 "templated": true
 },
 "self": {
 "href": "http://localhost:8080/employees/search"
 }
 }
}

After inserting a few example data, we are able to test our new query method by calling for example http://localhost:8080/employees/search/findByLastNameIgnoreCase?lastName=dOe

{
 "_embedded": {
 "employees": [
 {
  "firstName": "John",
  "lastName": "Doe",
  "salary": 1234.56,
  "dateOfBirth": "1980-05-24T00:00:00.000+0000",
  "hire": "2016-11-18T00:00:00.000+0000",
  "fire": null,
  "_links": {
   "self": {
    "href": "http://localhost:8080/employees/1"
   },
   "employee": {
    "href": "http://localhost:8080/employees/1"
   }
  }
 },
 {
  "firstName": "John",
  "lastName": "DOE",
  "salary": 1234.56,
  "dateOfBirth": "1980-05-24T00:00:00.000+0000",
  "hire": "2016-11-18T00:00:00.000+0000",
  "fire": null,
  "_links": {
   "self": {
    "href": "http://localhost:8080/employees/2"
   },
   "employee": {
    "href": "http://localhost:8080/employees/2"
   }
  }
 },
 {
  "firstName": "John",
  "lastName": "doe",
  "salary": 1234.56,
  "dateOfBirth": "1980-05-24T00:00:00.000+0000",
  "hire": "2016-11-18T00:00:00.000+0000",
  "fire": null,
  "_links": {
   "self": {
    "href": "http://localhost:8080/employees/3"
   },
   "employee": {
    "href": "http://localhost:8080/employees/3"
   }
  }
 }
 ]
 },
 "_links": {
  "self": {
   "href": "http://localhost:8080/employees/search/findByLastNameIgnoreCase?lastName=dOe"
  }
 }
}

The example code can be found here.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.