[英]ResourceSupport.getId() on Spring HATEOAS 1.x
I am learning how to use Spring Boot to build REST APIs through a written tutorial and HATEOAS is used at some point.我正在通过书面教程学习如何使用 Spring Boot 构建 REST API,并且在某些时候使用了 HATEOAS。 It seems the tutorial uses a now outdated version (0.x) since the classes Resource, Resources, ControllerLinkBuilder etc. weren't being found, so after some digging I found out 1.x had modified the structure and naming of some classes.
由于没有找到类 Resource、Resources、ControllerLinkBuilder 等,本教程似乎使用了一个现在过时的版本 (0.x),所以经过一番挖掘,我发现 1.x 修改了一些类的结构和命名。 I just swapped out every mention of a class/method with its updated version (Resource with EntityModel, etc.) and didn't run into much trouble until I got stuck at the part where a resource's "self" link was needed to generate an HTTP response for the POST command:
我只是用更新的版本(带有 EntityModel 的资源等)替换了对类/方法的所有提及,直到我卡在需要资源的“自我”链接来生成一个POST 命令的 HTTP 响应:
@PostMapping("/employees")
ResponseEntity<?> newEmployee(@RequestBody Employee newEmployee) throws URISyntaxException {
Resource<Employee> resource = assembler.toResource(repository.save(newEmployee));
return ResponseEntity
.created(new URI(resource.getId().expand().getHref()))
.body(resource);
}
Is there an equivalent for是否有等价物
resource.getId()
For EntityModel in HATEOAS 1.x?对于 HATEOAS 1.x 中的 EntityModel?
This is the class the "assembler" variable is an instance of:这是“汇编程序”变量是一个实例的类:
package payroll;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.RepresentationModelAssembler;
import org.springframework.stereotype.Component;
@Component
class EmployeeResourceAssembler implements RepresentationModelAssembler<Employee, EntityModel<Employee>> {
@Override
public EntityModel<Employee> toModel(Employee employee) {
return new EntityModel<>(employee,
linkTo(methodOn(EmployeeController.class).one(employee.getId())).withSelfRel(),
linkTo(methodOn(EmployeeController.class).all()).withRel("employees"));
}
}
Found it, that was equivalent to doing this in HATEOAS 1.x:找到了,这相当于在 HATEOAS 1.x 中执行此操作:
return ResponseEntity
.created(new URI(resource.getLink("self").orElse(new Link("self")).getHref()))
.body(resource);
Since getLink()
returns an Optional<Link>
I just had to add orElse()
case so that it's "unwrapped".由于
getLink()
返回一个Optional<Link>
我只需要添加orElse()
案例以便它“解包”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.