How to fech JPA entity from HATEOAS URI (self.href)
See original GitHub issueI really like the HATEOAS concept that URIs are used as IDs. For example when I have an POJO Entity Comment it can simply be referenced as /myBasePath/comments/4711
spring-hateoas has great support for building those URIs when I have an JPA entity:
Link entityUriLink = entityLinks.linkToSingleResource(Comment.class, comment.getId());
BUT there is no way for the other way round. There no (easy) way to get the JPA entity when you just have its URI.
Why and when is this necessary? In a custom rest controller, an enttiy URI might be passed as a @RequestParam
. Spring data rest actually IS able to fetch the entity from its plain (internal, numerical) ID. This works:
@BasePathAwareController
public class MyCustomController {
@RequestMapping("/customEndpoint")
public ResponseEntity customEndpoint(@RequestParam("commentId") CommentModel comment) { ... }
}
GET /myBasePath/customEndpoint?commentId=4711 <= works
GET /myBasePath/customEndpoint?commentId=/comments/4711 <= DOES NOT WORK
GET /myBasePath/customEndpoint?commentId=/myBasePath/comments/4711 <= DOES NOT WORK
GET /myBasePath/customEndpoint?commentId=http://localhost:8080/myBasePath/comments/4711 <= DOES NOT WORK
There would be org.springframework.data.rest.core.UriToEntityConverter
but this class is very difficult to create, because it needs so many dependencies (PersistentEntities, RepositoryInvokerFactory, Repositories)
I have a workaround, but an ugly one. You can configure your own conversionService
in a RepositoryRestConfigurer
. But then its an ugly parsing of IDs from String in there.
=> How to get the JPA entity when I only have the URI of it?
Issue Analytics
- State:
- Created 5 years ago
- Comments:8 (4 by maintainers)
Greg, this has been a concern that I brought up with version 0.11 or so. Without the ability to do round-trip mapping, the entire infrastructure is essentially useless because link handling devolves into a bunch of hand-parsing.
@Doogiemuc in SDR, you have
RepositoryEntityLinks
that lets you turn domain objects into links. That’s because SDR defines all the routes and can thus leverage metadata. And as you’ve noted, SDR also hasUriToEntityConverter
, which lets you go the other direction.But with Spring HATEOAS, the only place where routes are defined are in the annotations in your own custom controllers. Spring MVC/WebFlux (the underlying web stack) has no centralized route table that this data is gathered into, hence no way to do a reverse lookup.