View on GitHub

reading-notes

Spring RESTful Routing & Static Files

Spring RequestMapping

the annotation is used to map web requests to Spring Controller methods.

@RequestMapping Basics

@RequestMapping(value = "/ex/foos", method = RequestMethod.GET)
@ResponseBody
public String getFoosBySimplePath() {
    return "Get some Foos";
}

RequestMapping and HTTP Headers

@RequestMapping(
  value = "/ex/foos", 
  method = RequestMethod.GET, 
  produces = "application/json"
)

•if you used the old type of mapping with the headers attribute it will be converted to the new procedures way
procedures supports multiple values

RequestMapping With Path Variables

mapping URI can be bound to variables via the @PathVariable annotation.

@RequestMapping(value = "/ex/foos/{fooid}/bar/{barid}", method = GET)
@ResponseBody
public String getFoosBySimplePathWithPathVariables
  (@PathVariable long fooid, @PathVariable long barid) {
    return "Get a specific Bar with id=" + barid + 
      " from a Foo with id=" + fooid;
}

RequestMapping With Request Parameters

@RequestMapping(value = "/ex/bars", method = GET)
@ResponseBody
public String getBarBySimplePathWithRequestParam(
  @RequestParam("id") long id) {
    return "Get a specific Bar with id=" + id;
}

extracting the value of the id parameter using the @RequestParam(“id”) annotation in the controller method signature.

To send a request with the id parameter, we’ll use the parameter support in curl

RequestMapping Corner Cases

New Request Mapping Shortcuts

Accessing Data with JPA

Define a Simple Entity

create a class and annotate it with @Entity , indicating that it is a JPA entity, you store objects, each annotated as a JPA entity.

Create Simple Queries

Spring Data JPA focuses on using JPA to store data in a relational database. Its most compelling feature is the ability to create repository implementations automatically, at runtime, from a repository interface.

Create an Application Class

Spring Initializr creates a simple class for the application.
Now you need to modify the simple class that the Initializr created for you. To get output to the console

CrudRepository, JpaRepository, and PagingAndSortingRepository in Spring Data

JpaRepository – which extends PagingAndSortingRepository and the CrudRepository.

CrudRepository

CRUD functionality:

PagingAndSortingRepository

When using Pageable, we create a Pageable object with certain properties and we’ve to specify at least:

  1. Page size
  2. Current page number
  3. Sorting

JpaRepository

JPA methods: