Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While using Spring Data Rest after migrating an app to Spring Boot, I have observed that entity properties with @Id are no longer marshalled to JSON

This question is related to this SO question (Spring boot @ResponseBody doesn't serialize entity id). I have observed that after migrating an app to Spring Boot and using the spring-boot-starter-data-rest dependency, my entity @Id fields are no longer marshalled in the resulting JSON.

This is my request mapping and while debugging, I can see the data isn't being changed prior to returning it, so the @Id properties are being stripped later on.

@RequestMapping(method = RequestMethod.GET, produces = {"application/json"})
public PagedResources<Receipt> receipts(Pageable pageable, PagedResourcesAssembler assembler) {
    Page<Receipt> receipts = receiptRepository.findByStorerAndCreatedDateGreaterThanEqual("003845", createdStartDate, pageable);
    PagedResources<Receipt> pagedResources = assembler.toResource(receipts, receiptResourceAssembler);
    return pagedResources;
}

Is there a setting that would allow me to keep the @Id field in the resulting JSON because my app allows the user to search by that value.

Thanks :)

like image 314
Patrick Grimard Avatar asked Jul 24 '14 14:07

Patrick Grimard


3 Answers

By default Spring Data Rest does not spit out IDs. However you can selectively enable it through exposeIdsFor(..) method. You could do this in configuration, something like this

@Configuration public static class RepositoryConfig extends         RepositoryRestMvcConfiguration {      @Override     protected void configureRepositoryRestConfiguration(             RepositoryRestConfiguration config) {         config.exposeIdsFor(Class1.class, Class2.class);     } } 
like image 105
Stackee007 Avatar answered Sep 25 '22 16:09

Stackee007


As of Spring Data Rest 2.4 (which is a transitive dependency if using spring-boot 1.3.0.M5) you may use the RepositoryRestConfigurerAdapter. For instance,

@Configuration
class SpringDataRestConfig {

    @Bean
    public RepositoryRestConfigurer repositoryRestConfigurer() {

        return new RepositoryRestConfigurerAdapter() {
            @Override
            public void configureRepositoryRestConfiguration(
                                 RepositoryRestConfiguration config) {
                config.exposeIdsFor(Class1.class, Class2.class);
            }
        }

    }

}
like image 37
Ryan Parrish Avatar answered Sep 25 '22 16:09

Ryan Parrish


Before expose Id please read disussion: https://github.com/spring-projects/spring-hateoas/issues/66

In REST the id of a resource is its URI. The client doesn't explicitly use the id to build an url. You could, for example, replace your id for an uuid, for example. Or even change the url scheme.

like image 35
Grigory Kislin Avatar answered Sep 25 '22 16:09

Grigory Kislin