如何使 HATEOAS 呈现空的嵌入式数组

How to make HATEOAS render empty embedded array

通常 CollectionModel 将 return 一个 _embedded 数组,但在这个例子中:

@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");
    }

如果 productMaterials 为空 CollectionModel 将不会呈现 _embedded 数组,这会破坏客户端。有什么办法可以解决这个问题吗?

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);
        }
    }