[英]How to expose an entity via alternate keys with spring data rest
Spring-data-rest does a great job exposing entities via their primary key for GET
, PUT
and DELETE
etc. operations. Spring-data-rest通过其主键为
GET
, PUT
和DELETE
等操作公开实体。
/myentityies/123
It also exposes search operations. 它还暴露了搜索操作。
/myentities/search/byMyOtherKey?myOtherKey=123
In my case the entities have a number of alternate keys. 在我的例子中,实体有许多备用键。 The systems calling us, will know the objects by these IDs, rather than our internal primary key.
呼叫我们的系统将通过这些ID而不是我们的内部主键来了解对象。 Is it possible to expose the objects via another URL and have the
GET
, PUT
and DELETE
handled by the built-in spring-data-rest
controllers? 是否可以通过另一个URL公开对象,并通过内置的
spring-data-rest
控制器处理GET
, PUT
和DELETE
?
/myentities/myotherkey/456
We'd like to avoid forcing the calling systems to have to make two requests for each update. 我们希望避免强制调用系统必须为每次更新发出两个请求。
I've tried playing with @RestResource
path value, but there doesn't seem to be a way to add additional paths. 我尝试使用
@RestResource
路径值,但似乎没有办法添加其他路径。
I finally figured out how to do this! 我终于想出了如何做到这一点!
Add an implementation of BackendIdConverter to your Spring context. 将BackendIdConverter的实现添加到Spring上下文中。
@Component
public class BackendIdConverterImpl implements BackendIdConverter {
@Override
public boolean supports(Class<?> delimiter) {
return true; // Always convert.
}
@Override
public Serializable fromRequestId(String id, Class<?> entityType) {
// Convert from the external key to your internal key.
}
@Override
public String toRequestId(Serializable id, Class<?> entityType) {
// Convert from the internal key to your external key.
}
}
You think in URI, and Spring Data Rest in designed to think in relations. 您认为在URI中,Spring Data Rest旨在考虑关系。
There is no problem in declaring another controller, using @RepositoryRestController
mapped on 使用映射的
@RepositoryRestController
声明另一个控制器没有问题
/myentities/myotherkey/{otherKey}
but then, how will it be discovered by the client application ? 但是,客户端应用程序将如何发现它? To be consistent, you'll have to add a link to this controller in your resource mapping, with a custom
ResourceProcessor<Resource<Myentity>>
. 为了保持一致,您必须在资源映射中添加一个指向此控制器的链接,并使用自定义
ResourceProcessor<Resource<Myentity>>
。
But no pre-made stuff here. 但这里没有预制的东西。 In a REST environment, the ID of an entity is supposed to be its URI.
在REST环境中,实体的ID应该是其URI。 If you want to have another paradigm, then you will have to adapt it yourself, unfortunately.
如果你想拥有另一种范式,那么不幸的是你必须自己适应它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.