Expose all IDs when using Spring Data Rest

前端 未结 12 1718
北海茫月
北海茫月 2020-11-30 06:26

I\'d like to expose all IDs using a Spring Rest interface.

I know that per default an ID like this will not be exposed via the rest interface:

    @I         


        
相关标签:
12条回答
  • 2020-11-30 07:08

    You can add all your entity classes by exposeIdsFor. Replace "db.entity" to whick package you put your entities.

    @Configuration
    public class CustomRepositoryRestConfigurer extends RepositoryRestConfigurerAdapter {
        Logger logger = Logger.getLogger(this.getClass());
    
        @Override
        public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
            Set<String> classNameSet = ClassTool.getClassName("db.entity", false);
            for (String className : classNameSet) {
                try {
                    config.exposeIdsFor(Class.forName(className));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
    
            logger.info("exposeIdsFor : " + classNameSet);
        }
    }
    

    The ClassTool is my custom function to get class from given package, you can write by yourself.

    0 讨论(0)
  • 2020-11-30 07:08

    Please find a simple solution for this, avoiding to find entities related.

    @Component
    public class EntityExposingIdConfiguration extends RepositoryRestConfigurerAdapter {
    
        @Override
        public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
            try {
                Field exposeIdsFor = RepositoryRestConfiguration.class.getDeclaredField("exposeIdsFor");
                exposeIdsFor.setAccessible(true);
                ReflectionUtils.setField(exposeIdsFor, config, new ListAlwaysContains());
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
    
        class ListAlwaysContains extends ArrayList {
    
            @Override
            public boolean contains(Object o) {
                return true;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-30 07:11

    Currently, there is no way to do this provided by SDR. This issue on the SDR Jira tracker gives some explanation as to why this isn't (and perhaps shouldn't) be possible.

    The argument is basically that since the IDs are already contained within the self links in the response, you don't need to expose them as properties of the object itself.

    That said, you may be able to use reflection to retrieve all classes that have a javax.persistence.Id annotation and then call RepositoryRestConfiguration#exposeIdsFor(Class<?>... domainTypes).

    0 讨论(0)
  • 2020-11-30 07:15

    Try this configuration. It works perfectly fine for me.

    @Configuration
    public class RestConfiguration extends RepositoryRestConfigurerAdapter{
    
          @PersistenceContext
          private EntityManager entityManager;
    
          @Override
          public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
               //TODO: Expose for specific entity!
               //config.exposeIdsFor(Officer.class);
               //config.exposeIdsFor(Position.class);
    
               //TODO: Expose id for all entities!
               entityManager.getMetamodel().getEntities().forEach(entity->{
                    try {
                         System.out.println("Model: " + entity.getName());
                         Class<? extends Object> clazz = Class.forName(String.format("yourpackage.%s", entity.getName()));
                         config.exposeIdsFor(clazz);
                    } catch (Exception e) {
                         System.out.println(e.getMessage());
                    }
                });
        }
    }
    
    0 讨论(0)
  • 2020-11-30 07:16

    I discovered that if you name the @Id field 'Id' it will display in the JSON if you have a public getter for the Id. The Id will show up as a JSON key called 'id'

    For example: @Id @Column(name="PERSON_ROLE_ID") private Long Id;

    This also works for @EmbeddedId fields called 'Id' as well as long as it has a public getter. In this case the fields of the Id will show up as a JSON object.

    For example: @EmbeddedId private PrimaryKey Id;

    Surprisingly this is case sensitive, calling id 'id' doesn't work even though it would be a more conventional name for a Java field.

    I should say that I discovered this completely by accident so I don't know if this is an accepted convention or will work with previous or future versions of Spring Data and REST. Therefore I have included the relevant parts of my maven pom just incase it's sensittive to versions...

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc7</artifactId>
            <version>12.1.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
    </dependencies>
    
    0 讨论(0)
  • 2020-11-30 07:18

    Here is what worked perfectly for me (source here):

    @Configuration
    public class RepositoryRestConfig extends RepositoryRestConfigurerAdapter {
    
      @Override
      public void configureRepositoryRestConfiguration(final RepositoryRestConfiguration config) {
    
        final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
        provider.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
    
        final Set<BeanDefinition> beans = provider.findCandidateComponents("com.your.domain");
    
        for (final BeanDefinition bean : beans) {
          try {
            config.exposeIdsFor(Class.forName(bean.getBeanClassName()));
          } catch (final ClassNotFoundException e) {
            // Can't throw ClassNotFoundException due to the method signature. Need to cast it
            throw new IllegalStateException("Failed to expose `id` field due to", e);
          }
        }
      }
    }
    

    It finds all beans with the @Entity annotation and exposes them.

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