Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expose the resourceId with Spring Data Rest

I had was to expose the primary key which is annotated with @Id in entity.the ID field is only visible on the resource path, but not on the JSON body.

like image 854
Chandra Avatar asked Jan 24 '16 07:01

Chandra


People also ask

Is used for exposing spring data repositories over rest using Spring data rest?

Spring Data REST can be used to expose HATEOAS RESTful resources around Spring Data repositories. Without writing a lot of code, we can expose RESTful API around Spring Data Repositories.

Why use Spring data rest?

In general, Spring Data REST is built on top of the Spring Data project and makes it easy to build hypermedia-driven REST web services that connect to Spring Data repositories – all using HAL as the driving hypermedia type.

What is the use of spring boot starter data rest?

Spring Data REST builds on top of Spring Data repositories, analyzes your application's domain model and exposes hypermedia-driven HTTP resources for aggregates contained in the model.

What is rest repository?

Rest Repositories: The library that will allow you to expose your database as a RESTful API. JPA: The Java Persistence API library that will help you map SQL databases to objects and vice-versa. Lombok: Java annotation library that helps you code faster by reducing boilerplate code.


2 Answers

You can configure this using the RepositoryRestConfigurerAdapter on entity level.

@Configuration
public class ExposeEntityIdRestConfiguration extends RepositoryRestConfigurerAdapter {

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.exposeIdsFor(MyEntity.class);
    }
}

Be aware that using this you are working against the principles of spring-data-rest - sdr promotes hypermedia to be able to use an API by navigating between resources using links - here your resources are identified and referenced by links and thus the ids are not needed anymore. Using ids on your client pushes the complexity of constructing links to resources to the client. And the client should not be bothered with this knowledge.

like image 58
Mathias Dpunkt Avatar answered Sep 28 '22 11:09

Mathias Dpunkt


The best solution would be not to using the IDs of your entities, and use the link references the hypermedia provides. You just need to parse your JSON accordingly to the HAL specification used by Spring Data Rest.

like image 26
nahueltori Avatar answered Sep 28 '22 11:09

nahueltori