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:
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(unique=true, nullable=false) private Long id;
I'm aware that I can use this to expose the ID for User
:
@Configuration public class RepositoryConfig extends RepositoryRestMvcConfiguration { @Override protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { config.exposeIdsFor(User.class); } }
But is there an easy way to expose all IDs without manually maintaining a list in this configureRepositoryRestConfiguration
method?
Spring Data REST can be used to expose HATEOAS RESTful resources around Spring Data repositories. Without writing a lot of code, we can expose RESTful API around Spring Data Repositories.
Real-world applications should avoid using Spring Data REST because the entities are exposed as RESTful Services. The two most critical considerations in designing a RESTful service are the domain model and the consumers.
@RepositoryRestResource is used to set options on the public Repository interface - it will automatically create endpoints as appropriate based on the type of Repository that is being extended (i.e. CrudRepository/PagingAndSortingRepository/etc).
CrudRepository mainly provides CRUD operations. PagingAndSortingRepository provide methods to perform pagination and sorting of records. JpaRepository provides JPA related methods such as flushing the persistence context and deleting of records in batch.
If you want to expose the id field for all your entity classes:
import java.util.stream.Collectors; import javax.persistence.EntityManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter; @Configuration public class MyRepositoryRestConfigurerAdapter extends RepositoryRestConfigurerAdapter { @Autowired private EntityManager entityManager; @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { config.exposeIdsFor(entityManager.getMetamodel().getEntities().stream().map(e -> e.getJavaType()).collect(Collectors.toList()).toArray(new Class[0])); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With