Spring 如何使HATEOAS呈现空嵌入数组
通常,Spring 如何使HATEOAS呈现空嵌入数组,spring,spring-boot,spring-hateoas,Spring,Spring Boot,Spring Hateoas,通常,CollectionModel将返回一个\u嵌入的数组,但在本例中: @GetMapping("/{id}/productMaterials") public ResponseEntity<?> getProductMaterials(@PathVariable Integer id) { Optional<Material> optionalMaterial = materialRepository.findById(i
CollectionModel
将返回一个\u嵌入的
数组,但在本例中:
@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");
}
@GetMapping(“/{id}/productMaterials”)
公共响应属性getProductMaterials(@PathVariable整数id){
可选选项material=materialRepository.findById(id);
if(可选材质.isPresent()){
List productMaterials=optionalMaterial.get().getProductMaterials();
集合模型productMaterialModels=
新的ProductMaterialModelAssembler(ProductMaterialController.class,ProductMaterialModel.class)。
收集模型(产品材料);
返回ResponseEntity.ok().body(productMaterialModels);
}
返回ResponseEntity.badRequest().body(“无此类材料”);
}
如果productMaterials
为空CollectionModel
将不会呈现嵌入的\u
数组,这将破坏客户端。有没有办法解决这个问题?if(optionalMaterial.isPresent()){
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);
}
}
List productMaterials=optionalMaterial.get().getProductMaterials();
集合模型productMaterialModels=
新的ProductMaterialModelAssembler(ProductMaterialController.class,ProductMaterialModel.class)。
收集模型(产品材料);
if(productMaterialModels.isEmpty()){
EmbeddedWrappers-wrappers=新的EmbeddedWrappers(false);
EmbeddedWrapper=wrappers.emptyCollectionOf(ProductMaterialModel.class);
Resources Resources=新资源(Arrays.asList(wrapper));
返回ResponseEntity.ok(新资源(Resources));
}否则{
返回ResponseEntity.ok().body(productMaterialModels);
}
}
您必须使用EmbeddedWrapper,您应该显式标记您的资源,以呈现一个空的_embeddedarray谢谢您的回答。你能告诉我怎么写吗?我不知道作者在说什么:((谢谢,它起作用了:))既然资源已经不存在了,我就稍微修改一下代码。现在流行的是spring Hateo吗?所有的解决方案似乎都不受欢迎,一点也不优雅。