Spring REST response differs in user controller

I have several controllers that automatically create endpoints REST.

@RepositoryRestResource(collectionResourceRel = "books", path = "books")
public interface BooksRepository extends CrudRepository<Books, Integer> {
    public Page<Books> findTopByNameOrderByFilenameDesc(String name);
}

When I am: http: // localhost: 8080 / Books

I'm coming back:

{
    "_embedded": {
        "Books": [{
            "id": ,
            "filename": "Test123",
            "name": "test123",
            "_links": {
                "self": {
                    "href": "http://localhost:8080/books/123"
                },
                "Books": {
                    "href": "http://localhost:8080/books/123"
                }
            }
        }]
    },
    "_links": {
        "self": {
            "href": "http://localhost:8080/books"
        },
        "profile": {
            "href": "http://localhost:8080/profile/books"
        },
        "search": {
            "href": "http://localhost:8080/books/search"
        },
        "page": {
            "size": 20,
            "totalElements": 81,
            "totalPages": 5,
            "number": 0
        }
    }
}

When I create my own controller:

@Controller
@RequestMapping(value = "/CustomBooks")
public class CustomBooksController {
    @Autowired
    public CustomBookService customBookService;

    @RequestMapping("/search")
    @ResponseBody
    public Page<Book> search(@RequestParam(value = "q", required = false) String query,
                                 @PageableDefault(page = 0, size = 20) Pageable pageable) {
        return customBookService.findAll();
    }
}

I will get a response that does not look like an automatically generated controller response:

{
    "content": [{
        "filename": "Test123",
        "name" : "test123"
    }],
    "totalPages": 5,
    "totalElements": 81,
    "size": 20,
    "number": 0,
}

What do I need to do so that my answer looks like an automatically generated answer? I want to keep it consistent, so I don't need to rewrite the code for another answer. Should I do it differently?


Edit: Found the following: Enable HAL serialization in Spring Download for custom controller method

, REST, : PersistentEntityResourceAssembler. Google PersistentEntityResourceAssembler, (, , ).

+4
1

@chrylis, @Controller @RepositoryRestController spring -data-rest, ResourceProcessors .

, HATEOAS (, spring -data-rest BooksRepository), HttpEntity<PagedResources<Resource<Books>>> PagedResources:

  • .

    @Autowired private PagedResourcesAssembler<Books> bookAssembler;

  • return new ResponseEntity<>(bookAssembler.toResource(customBookService.findAll()), HttpStatus.OK);

org.springframework.hateoas.Resources, "_embedded" "_links.

+5

Source: https://habr.com/ru/post/1662583/


All Articles