본문 바로가기
개발자의 정보/Java & framework

[spring-boot-data-rest] How to expose IDs for all

by pastory 2020. 2. 1.

spring data rest 사용시 일괄적용으로 @ID 컬럼을 함께 데이터로 내보내고 싶을 때 나는 아래의 코드를 사용한다.

 

Append configuration file to spring-configuration.

import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.rest.core.config.RepositoryRestConfiguration;import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;import javax.persistence.Entity;import javax.persistence.EntityManagerFactory;import javax.persistence.metamodel.ManagedType;import javax.persistence.metamodel.Metamodel;import java.util.ArrayList;import java.util.List;@Configurationpublic class RestConfig extends RepositoryRestConfigurerAdapter {
   private List<Class<?>> getAllManagedEntityTypes(EntityManagerFactory entityManagerFactory) {

      List<Class<?>> entityClasses = new ArrayList<>();
      Metamodel metamodel = entityManagerFactory.getMetamodel();
      for (ManagedType<?> managedType : metamodel.getManagedTypes()) {

         Class<?> javaType = managedType.getJavaType();
         if (javaType.isAnnotationPresent(Entity.class)) {

            entityClasses.add(managedType.getJavaType());
         }
      }

      return entityClasses;
   }
  

   @Bean
   public RepositoryRestConfigurer repositoryRestConfigurer(EntityManagerFactory entityManagerFactory) {

      List<Class<?>> entityClasses = getAllManagedEntityTypes(entityManagerFactory);
     
      return new RepositoryRestConfigurerAdapter() {
        

         @Override
         public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
            for (Class<?> entityClass : entityClasses) {

               config.exposeIdsFor(entityClass);
            }
         }

      };
   }
}

댓글