Spring HATEOAS RepresentationModelAssembler toCollectionModel()

标签 spring spring-boot rest spring-hateoas hateoas

我正在创建 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/

相关文章:

java - Spring 启动服务器接收带有 %20 而不是空间的参数

java - `NullPoinerException` 依赖于 `@Autowired`

java - 处理无效 REST API 参数的内部 Java 代码最佳实践

java - 带参数的 Jersey 构造函数

java - 强制 hibernate 读取数据库并且不返回缓存的实体

spring - Groovy:Lombok @NoArgsConstructor 不创建默认构造函数

java - 如何在 Spring Boot 上以相同的方法回滚 2 个事务

spring-boot - 服务实现 - 如何根据 application.properties 属性选择使用哪个服务实现?

java - 在 sessionFactory 初始化之前更改实体模式名称

regex - 在 JSTL 中解析请求 URL