为嵌套关系配置带有多段的@repositoryrestresource路径

8e2ybdfx  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(331)

我为一个地址众多的客户创建了2个hateos@repositoryrestresource:

class Customer {
  ...
  Long id;
  @OneToMany(
  Set<Address> addresses;
  ...
}

class Address {
  ...
  Long id;
  ...
}

@RepositoryRestResource(path = "customers")
public interface CustomerRepository extends PagingAndSortingRepository<Customer, Long> {
}

@RepositoryRestResource(path = "addresses")
public interface AddressRepository extends PagingAndSortingRepository<Address, Long> {
}

我能够得到一个地址实体与下列多段路径

Get Address 1 of Customer 1: GET /customers/1/adresses/1

但是。。。我无法使用相同的多段路径修补、放置或删除地址

Update Address 1 of Customer 1: PATCH, PUT or DELETE /customers/1/adresses/1

我总是收到404-找不到。它只有在使用地址端点时才有效

Update Address 1 : PATCH, PUT or DELETE /adresses/1

有没有办法配置@repositoryrestresource以便更新/删除地址(或通过客户端点(/customers/{customerid}/addresses/{addressid})与客户相关的任何实体)?
当做
代码可在https://github.com/fdlessard/spring-boot-repository-rest-resource

cczfrluj

cczfrluj1#

当你得到 /customers/1/addresses/1 ,响应json应为

{
  "country": "XYZ",
  "_links": {
    "self": {
      "href": "http://localhost:8888/addresses/1" <-- here
    },
    "address": {
      "href": "http://localhost:8888/addresses/1"
    }
  }
}

使用链接 self ,也就是说, http://localhost:8888/addresses/1 更新。
事实上,当你 /customers/1/addresses ,数组 addresses 作为回应,json已经给出了真正的uri /addresses/1 .

{
  "_embedded": {
    "addresses": [
      {
        "country": "XYZ",
        "_links": {
          "self": {
            "href": "http://localhost:8888/addresses/1"  <-- here
          },
          "address": {
            "href": "http://localhost:8888/addresses/1"
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8888/customers/1/addresses"
    }
  }
}

记住,当使用hateoas时,发现链接并遵循href,而不是硬编码uri。看到了吗https://docs.spring.io/spring-hateoas/docs/current/reference/html/#client.link-发现者

相关问题