gpt4 book ai didi

java - PersonResource 与 spring-hateoas 中的 Person 是一样的吗

转载 作者:行者123 更新时间:2023-12-02 12:13:57 25 4
gpt4 key购买 nike

我有一个包含 id、firstName、lastName 的 Person.java 类:

根据文档,如果我希望有 hatoas 链接、分页和计数,我应该使用 PersonResource:

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

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

最佳答案

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

正如 Spring HATEOAS API 文档中提到的, Resource围绕域对象添加链接的包装器。资源是 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 通常用于访问和更新存储在数据库表 (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);
}

}

关于java - PersonResource 与 spring-hateoas 中的 Person 是一样的吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46327933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com