我正在创建 Spring Boot HATEOAS REST 应用程序。下面的代码显示了我如何添加链接,同时为特定员工发送 GET 请求。我正在使用RepresentationModelAssembler
toModel
功能。还有toCollectionModel
函数覆盖,我想用它来转换 List<Employees>
到集合模型。 -> 这将在/Employees/all 端点中返回。
我不知道该怎么做。 所以我需要的是通过List<Employees>
,那么所有列表元素都需要通过 toModel
进行处理函数,然后,就像在 toModel 函数中一样,我需要添加更多链接到它 -> 链接到整个新集合(而不是单个项目)。
期待您的答复!
@Component
public class EmployeeModelAssembler implements RepresentationModelAssembler<Employee, EntityModel<Employee>> {
@Override
public EntityModel<Employee> toModel(Employee employee) {
EntityModel<Employee> employeeEntityModel = EntityModel.of(employee);
Link selfLink = linkTo(methodOn(EmployeeController.class).getEmployeeById(employee.getId())).withSelfRel();
employeeEntityModel.add(selfLink);
return employeeEntityModel;
}
@Override
public CollectionModel<EntityModel<Employee>> toCollectionModel(Iterable<? extends Employee> entities) {
?? ?? ??
}
}
最佳答案
你可以使用这样的东西:
@GetMapping(produces = { "application/hal+json" })
public CollectionModel<Customer> getAllCustomers() {
List<Customer> allCustomers = customerService.allCustomers();
for (Customer customer : allCustomers) {
String customerId = customer.getCustomerId();
Link selfLink = linkTo(CustomerController.class).slash(customerId).withSelfRel();
customer.add(selfLink);
if (orderService.getAllOrdersForCustomer(customerId).size() > 0) {
Link ordersLink = linkTo(methodOn(CustomerController.class)
.getOrdersForCustomer(customerId)).withRel("allOrders");
customer.add(ordersLink);
}
}
Link link = linkTo(CustomerController.class).withSelfRel();
CollectionModel<Customer> result = CollectionModel.of(allCustomers, link);
return result;
}
访问https://www.baeldung.com/spring-hateoas-tutorial#springhateoasinaction详细解释
关于Spring HATEOAS RepresentationModelAssembler toCollectionModel(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62467638/