Enable HAL serialization in Spring Boot for custom controller method

后端 未结 3 673
清歌不尽
清歌不尽 2020-11-29 06:47

I\'m trying to build a RESTful API with Spring Boot using spring-boot-starter-data-rest. There are some entities: accounts, transactions, categories and users - just the usu

3条回答
  •  余生分开走
    2020-11-29 07:35

    To use PersistentEntityResourceAssembler in the controller we should mark it as @RepositoryRestController

    @RestController
    @RequestMapping("/categories")
    @RepositoryRestController
    public class CategoryController implements ValidableController {
    
    // dependencies
    
    @RequestMapping(method = POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity create(@Valid @RequestBody CategoryForm category,
                                                           BindingResult validation,
                                                           PersistentEntityResourceAssembler resourceAssembler)
    {
        validate(validation);
        Category entity = categoryConverter.convert(category);
        entity = categoryService.save(entity);
        return ResponseEntity.ok(resourceAssembler.toFullResource(entity));
    }
    

    It builds pretty nice HAL styled response

    {
    "createdTime": "2018-07-24T00:55:32.854",
    "updatedTime": "2018-07-24T00:55:32.855",
    "name": "cfvfcdfgdfdfdfs32",
    "options": [
        "aaa",
        "bbb"
    ],
    "_links": {
        "self": {
            "href": "http://localhost:8080/shop/categories/34"
        },
        "category": {
            "href": "http://localhost:8080/shop/categories/34{?projection}",
            "templated": true
        },
        "products": {
            "href": "http://localhost:8080/shop/categories/34/products"
        },
        "categories": {
            "href": "http://localhost:8080/shop/categories/34/categories{?projection}",
            "templated": true
        },
        "parent": {
            "href": "http://localhost:8080/shop/categories/34/parent{?projection}",
            "templated": true
        }
    }
    

    }

提交回复
热议问题