I am using Spring Data JPA to manage a JPA entity and Spring Data Rest exports the repository into a REST API.
I am also building a custom controller where I want to take the URI of the entity (HAL link) and automatically map it to entity object via the CrudRepository
.
CustomController
@RequestMapping(path = MeLinks.ELEVATE, method = RequestMethod.PUT, consumes = RestMediaTypes.TEXT_URI_LIST_VALUE)
HttpEntity<?> elevate(@RequestBody @Valid CollectionModel<Contact> contact) {
...
}
When trying to PUT
a contact link like http://localhost:8080/contacts/1
with Content-Type text/uri-list
, I am able to access the link using contact.getLinks()
but not the Contact object itself.
Is it possible for Spring Data Rest to automatically infer the entity from the URI? I am aware of an in-built UriToEntityConverter
but how do I use it?
Edit
Here is an attempt that works but doesn't really solve the problem gracefully.
Below code initializes a UriToEntityConverter
and converts the incoming URI to domain object.
@Autowired
private ApplicationContext applicationContext;
@Autowired
private MappingContext<?, ?> mappingContext;
@RequestMapping(path = MeLinks.ELEVATE, method = RequestMethod.PUT, consumes = RestMediaTypes.TEXT_URI_LIST_VALUE)
HttpEntity<?> elevate(@RequestBody @Valid CollectionModel<Contact> uris) {
URI uri = URI.create(uris.getLinks().get(0).getHref());
Repositories repositories = new Repositories(applicationContext);
PersistentEntity<?,?> contactPersistentEntity = repositories.getPersistentEntity(Contact.class);
UriToEntityConverter uriToEntityConverter = new UriToEntityConverter(
new PersistentEntities(Collections.singleton(mappingContext)),
new DefaultRepositoryInvokerFactory(repositories),
repositories);
Contact t = (Contact) uriToEntityConverter.convert(uri, TypeDescriptor.valueOf(URI.class), TypeDescriptor.valueOf(Contact.class));
}
As you can imagine, fetching the domain object from the Repository
would be much easier than doing above. Also this works assuming the URI uses the ID
as unique part of the link. In my case I have customized it to use a UUID instead. So default behaviour of UriToEntityConverter
would not work.
NOTE: Resources
class has been renamed to CollectionModel
with HATEOAS first release.
http://localhost:8080/contacts/1/childEntity
) I searched around and found nothing so far. – BreatheRepositoryRestController
? – EbchildEntity
as aLong
, as if it were acontact
id I suppose.childEntity
does have a repository but no custom link. – BreatheUriToEntityConverter
is meant to parse only root URIs. So in your case the URI to parse should behttp://localhost:8080/child_entities/1
or similar. – Eb