spring - RepositoryRestResource注释中的collectionResourceRel等可选元素中的 "rel"是什么意思?

标签 spring spring-boot spring-data-rest

您能帮我理解 RepositoryRestResource 注释的 collectionResourceRel 中提到的可选元素“rel”的含义吗? 我已经浏览过Java文档here .

以下是文档中的内容。

collectionResourceRel The rel value to use when generating links to the collection resource.

最佳答案

基本上 rel@RestResource 注释的属性。意思是“关系”

例如订单可能具有将订单链接到其客户的 "rel": "customer" 关系。

来自https://docs.spring.io/spring-data/rest/docs/current/reference/html/ :

例如,在默认配置中,如果您向 http://localhost:8080/persons/search 发出请求以了解公开了哪些查询方法,您将得到一个列表类似于以下的链接:

{
  "_links" : {
    "findByName" : {
      "href" : "http://localhost:8080/persons/search/findByName"
    }
  }
}

要更改 rel 值,请使用 @RestResource 注释上的 rel 属性,如以下示例所示:

@RepositoryRestResource(path = "people")
interface PersonRepository extends CrudRepository<Person, Long> {

  @RestResource(path = "names", rel = "names")
  List<Person> findByName(String name);
}

前面的示例产生以下链接值:

{
  "_links" : {
    "names" : {
      "href" : "http://localhost:8080/persons/search/names"
    }
  }
}

您可以更改存储库的 rel,如以下示例所示:

@RepositoryRestResource(path = "people", rel = "people")
interface PersonRepository extends CrudRepository<Person, Long> {

  @RestResource(path = "names", rel = "names")
  List<Person> findByName(String name);
}

更改存储库的 rel 会更改顶级名称,如以下示例输出所示:

{
  "_links" : {
    "people" : {  // rel = "people"
      "href" : "http://localhost:8080/people"
    },
    …
  }
}

rel = "people" 将该链接的名称更改为 people

问:您是否有一个示例显示“订单可能具有将订单链接到其客户的“rel”:“customer”关系。”?是否也考虑实体之间的关系,例如OneToMany、ManyToMany等。

它与OneToMany、ManyToMany等实体之间的关系不同。

关系描述了当前资源与目标资源如何相关。

这是 https://restfulapi.net/hateoas/ 中的一个很好的例子理解rel:

下面给出的 JSON 响应可能来自像 HTTP GET http://api.domain.com/management/departments/10 这样的 API

{
    "departmentId": 10,
    "departmentName": "Administration",
    "locationId": 1700,
    "managerId": 200,
    "links": [
        {
            "href": "10/employees",
            "rel": "employees",
            "type" : "GET"
        }
    ]
}

在上例中,服务器返回的响应中包含员工资源10/employees的超媒体链接,客户端可以遍历该链接来读取属于该部门的员工。

它位于表示层和数据层之间。借助 rel 和其他属性创建的链接:

{
    "href": "10/employees",
    "rel": "employees",
    "type" : "GET"
}

帮助应用程序向正确的方向(存储库、方法等)检索数据(属于该部门的员工)

根据您的设计,您还可以在数据层中的实体之间创建关系。但这些是不同的事情。

关于spring - RepositoryRestResource注释中的collectionResourceRel等可选元素中的 "rel"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56379876/

相关文章:

java - 错误 org.hibernate.util.JDBCExceptionReporter - 通信链路故障

java - 假装: Retry depending on response status

java - 无法在 Spring Boot Gradle 项目中导入 HATEOAS 元素

spring - VIEW表什么时候计算或改变值?

java - Spring JPA Repository 上的 API 数量是否会影响启动时间?

java - 为什么 Consul 尝试连接到我的数据库?

java - 访问外部 Spring Boot Java 项目中 application.properties 的属性

spring - 使用 Spring Data JPA 选择一列

java - 如何在 Spring data rest 中返回深层嵌套投影?

spring - NoClassDefFounderror - Spring JDBC