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

前端 未结 5 1668
逝去的感伤
逝去的感伤 2020-11-28 12:03

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 usi

相关标签:
5条回答
  • 2020-11-28 12:32

    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);
                }
            }
    
        }
    
    }
    
    0 讨论(0)
  • 2020-11-28 12:32

    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.

    0 讨论(0)
  • 2020-11-28 12:38

    @Id annotation in your model class does the magic.

    public class Location {
    
        @Id
        private String woeid;
        private String locationName;
    

    Then your mongo object will look like this:

    {
        "_id" : "2487889",
        "_class" : "com.agilisys.weatherdashboard.Location",
        "locationName" : "San Diego, CA"
    }
    
    0 讨论(0)
  • 2020-11-28 12:39

    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);
        }
    }
    
    0 讨论(0)
  • 2020-11-28 12:39

    put @getter, @setters and it will be exposed to json results, hope it would help you

    0 讨论(0)
提交回复
热议问题