PersonResource 是否与 spring-hateoas 中的 Person 相同

is PersonResource the same thing as Person in spring-hateoas

我有一个 Person.java class 包含 id,firstName,lastName:

根据文档,如果我希望使用 hateoas link、分页和计数,我应该使用 PersonResource:

https://docs.spring.io/spring-hateoas/docs/current/reference/html/#fundamentals.resources

Person一样吗? 我应该如何处理我的 id,ResourceSupport 已经实现了 getId() 方法。

你的域对象的id和REST资源的id是两个完全不同的东西。

如 Spring HATEOAS API 文档中所述,Resource 域对象的包装器,将 link 添加到其中。 资源是 REST 的基本概念。这是 an object with a type, associated data, relationships to other resources, and a set of methods that operate on it.

基本上,它的 ID 是您用来与 GET/PUT/POST/DELETE 方法交互的 URL。

包装到资源 (PersonResource) 中的是您的域对象 (Person),一个具有属性和 getters/setters :

的 POJO
// simple definition of a Person Resource in Spring
public class PersonResource extends Resource<Person> {

    public PersonResource(Person content, Link... links) {
        super(content, links);
    }

}

public class Person {
    ...
    String name;
    Integer age;
    // getters/setters omitted for clarity
}

REST API 通常用于访问和更新存储在数据库 table (SQL) 或集合 (NoSQL) 中的数据。这样的实体有一个唯一的 id,你映射到你的 POJO 的 id 属性:

public class Person {
    @Id
    String id;
    String name;
    Integer age;
    // getters/setters omitted for clarity
}

默认情况下,当您询问您的 REST API、Spring Data Rest 甚至不会公开您的实体 ID(在 REST 上下文中它没有意义,重要的是您如何识别资源):

获取 http://localhost:8080/person/1

{
    "name":"Ron Swanson",
    "age" : ...
    "_links":{
        "self":{
            "href":"http://localhost:8080/person/1" // the resource id
         }
    }
}

仅供参考,如果您调整配置,可以提供实体 ID:

@Configuration
public class CustomRepositoryRestConfiguration extends RepositoryRestConfigurerAdapter {

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration configuration) {
        configuration.exposeIdsFor(Person.class);
    }

}