【问题标题】:Spring HATEOAS RepresentationModelAssembler toCollectionModel()Spring HATEOAS RepresentationModelAssembler toCollectionModel()
【发布时间】:2020-06-19 09:49:45
【问题描述】:

我正在创建 Spring Boot HATEOAS REST 应用程序。下面的代码显示了我如何添加链接,同时为特定员工发送 GET 请求。我正在使用RepresentationModelAssemblertoModel 函数。还有toCollectionModel 函数可以覆盖,我想用它来将List<Employees> 转换为CollectionModel。 -> 这将在 /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) {

        ?? ?? ??

    }
}

【问题讨论】:

    标签: spring spring-boot rest spring-hateoas hateoas


    【解决方案1】:

    你可以这样使用:

    @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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      • 2011-11-02
      • 2014-03-07
      • 2016-04-14
      • 2019-10-08
      • 2014-07-05
      • 2018-07-23
      相关资源
      最近更新 更多