为嵌套关系配置多段 @RepositoryRestResource 路径
Posted
技术标签:
【中文标题】为嵌套关系配置多段 @RepositoryRestResource 路径【英文标题】:Configuring @RepositoryRestResource path with multi-segment for nested relationships 【发布时间】:2021-05-14 16:43:04 【问题描述】:我为拥有多个地址的客户创建了 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 - Not Found。仅当我使用地址端点时才有效
Update Address 1 : PATCH, PUT or DELETE /adresses/1
有没有办法配置 @RepositoryRestResource 以便我可以更新/删除地址(或通过客户端点 (/customers/customerId/addresses/addressId) 与客户相关的任何实体)?
问候
代码可在https://github.com/fdlessard/spring-boot-repository-rest-resource获取
【问题讨论】:
【参考方案1】:当你 GET /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
进行更新。
实际上,当您 GET /customers/1/addresses
时,响应 JSON 的数组 addresses
已经为您提供了真正的 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-discoverer
【讨论】:
以上是关于为嵌套关系配置多段 @RepositoryRestResource 路径的主要内容,如果未能解决你的问题,请参考以下文章