12

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.

Mathias Dpunkt
  • 11,594
  • 4
  • 45
  • 70
Chandra
  • 1,722
  • 16
  • 19
  • Possible duplicate of [Spring boot @ResponseBody doesn't serialize entity id](https://stackoverflow.com/questions/24839760/spring-boot-responsebody-doesnt-serialize-entity-id) – lcnicolau Mar 10 '19 at 00:32

2 Answers2

14

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.

Mathias Dpunkt
  • 11,594
  • 4
  • 45
  • 70
  • 4
    Is there a way to expose id's of all your entities at once? For e.g. setting in config? – thorinkor Jul 21 '16 at 12:07
  • How can I do it for all the entities at once? We have many package this module doesn't know about. – Dimitri Kopriwa Dec 14 '17 at 14:27
  • 3
    `RepositoryRestConfigurerAdapter` is now deprecated (since 3.1). Implement `RepositoryRestConfigurer` instead by overriding the same method. – James Feb 22 '19 at 17:58
1

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.

nahueltori
  • 19
  • 5