1

Usually CollectionModel will return an _embedded array, but in this example:

@GetMapping("/{id}/productMaterials")
    public ResponseEntity<?> getProductMaterials(@PathVariable Integer id) {
        Optional<Material> optionalMaterial = materialRepository.findById(id);
        if (optionalMaterial.isPresent()) {
            List<ProductMaterial> productMaterials = optionalMaterial.get().getProductMaterials();
            CollectionModel<ProductMaterialModel> productMaterialModels =
                    new ProductMaterialModelAssembler(ProductMaterialController.class, ProductMaterialModel.class).
                            toCollectionModel(productMaterials);
            return ResponseEntity.ok().body(productMaterialModels);
        }
        return ResponseEntity.badRequest().body("no such material");
    }

if the productMaterials is empty CollectionModel will not render the _embedded array which will break the client. Is there any ways to fix this?

La Hai
  • 113
  • 2
  • 12
  • you will have to use an EmbeddedWrapper https://stackoverflow.com/questions/30286795/how-to-force-spring-hateoas-resources-to-render-an-empty-embedded-array you should mark you resource explicitly to render an empty _embedded array – Amr Alaa Nov 01 '20 at 08:44
  • Thank you for your answer. Could you show me how to write it? I have no idea what the author was talking about :(( – La Hai Nov 01 '20 at 09:03

1 Answers1

3
if (optionalMaterial.isPresent()) {
        List<ProductMaterial> productMaterials = optionalMaterial.get().getProductMaterials();
        CollectionModel<ProductMaterialModel> productMaterialModels =
                new ProductMaterialModelAssembler(ProductMaterialController.class, ProductMaterialModel.class).
                        toCollectionModel(productMaterials);
        if(productMaterialModels.isEmpty()) {
            EmbeddedWrappers wrappers = new EmbeddedWrappers(false);
            EmbeddedWrapper wrapper = wrappers.emptyCollectionOf(ProductMaterialModel.class);
            Resources<Object> resources = new Resources<>(Arrays.asList(wrapper));
            return ResponseEntity.ok(new Resources<>(resources));
        } else {
            return ResponseEntity.ok().body(productMaterialModels);
        }
    }    
Amr Alaa
  • 545
  • 3
  • 7
  • Thank you. it worked :)) since the ```Resources``` does not exist anymore, i change the code a little bit – La Hai Nov 01 '20 at 10:41
  • Is spring HATEOAS popular right now? All the solutions seem to be deprecated and _not elegant_ at all. – La Hai Nov 01 '20 at 10:48
  • @LaHai how did you change the code? I can't find the `Resources` class. – Raman Dec 30 '21 at 19:07
  • 1
    @Raman Happy new year. I believe it's `CollectionModel` now. You can find the changes in [here](https://docs.spring.io/spring-hateoas/docs/current/reference/html/#migrate-to-1.0.changes) – La Hai Jan 04 '22 at 23:23