Search code examples
springhateoasspring-hateoas

How does linkForSingleResource work?


I can understand this code finds the BookController because I do @ExposesResourceFor(Book.class) before BookController but how does it know which method/URL to resolve into?

entityLinks.linkForSingleResource(book).toUri();

and this resolves into 127.0.0.1:8080/books/5

Does it just add /id to the url and doesn't check methods at all?


Solution

  • The Spring HATEOAS documentation has a chapter on EntityLinks that shows an example.

    The documentation on ControllerEntityLinks contains more details about the expected URI structure. There needs to be one empty mapping for the collection and one mapping with an id path variable for individual resources.

    @Controller
    @ExposesResourceFor(Order.class)
    @RequestMapping("/orders")
    class OrderController {
    
      //The collection resource
      @RequestMapping
      ResponseEntity orders(…) { … }
    
      //Individual resources
      @RequestMapping("/{id}")
      ResponseEntity order(@PathVariable("id") … ) { … }  
    

    }