Working with Spring Data REST
1. Adding Spring Data REST Dependencies
Example: Spring Data REST dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
| Feature | Provided |
|---|---|
| HAL+JSON | Default media type |
| HATEOAS | Resource links auto-generated |
| Pageable | ?page=0&size=10&sort=name,asc |
2. Exposing Repository REST Endpoints
Example: Auto-exposed REST repository
public interface PersonRepository extends JpaRepository<Person, Long> {
// Auto-exposed at /persons (collection) and /persons/{id} (item)
}
| Endpoint | Method |
|---|---|
/persons |
GET (page), POST (create) |
/persons/{id} |
GET, PUT, PATCH, DELETE |
/persons/search/... |
Derived query exposure |
3. Customizing Base Path
Example: Configure Data REST base path
spring:
data:
rest:
base-path: /api
default-page-size: 20
max-page-size: 100
4. Customizing Resource Names (@RepositoryRestResource)
Example: Custom path, rel, and hide endpoint
@RepositoryRestResource(path="people", collectionResourceRel="people")
public interface PersonRepository extends JpaRepository<Person, Long> {
@RestResource(path="byEmail", rel="byEmail")
Optional<Person> findByEmail(@Param("email") String email);
@RestResource(exported=false) // hide from REST
void deleteAll();
}
5. Handling Projections and Excerpts
Example: Projection with computed SpEL field
@Projection(name="summary", types=Person.class)
public interface PersonSummary {
String getFullName();
@Value("#{target.firstName + ' ' + target.lastName}") String getFullNameComputed();
}
// Use: GET /people/1?projection=summary
| Annotation | Use |
|---|---|
@Projection |
Defines a projection interface |
excerptProjection |
Default projection on collection |
6. Implementing Custom Handlers (@RepositoryEventHandler)
Example: Auto-assign UUID before create
@Component
@RepositoryEventHandler(Person.class)
public class PersonEventHandler {
@HandleBeforeCreate void beforeCreate(Person p) { p.setUuid(UUID.randomUUID()); }
@HandleAfterDelete void afterDelete(Person p) { /* audit */ }
}
| Event | Phase |
|---|---|
@HandleBefore/After Create |
Save |
@HandleBefore/After Save |
Update |
@HandleBefore/After Delete |
Delete |
@HandleBefore/After LinkSave |
Association |
7. Securing REST Endpoints
Example: Method-level security on repository
@PreAuthorize("hasRole('ADMIN')")
public interface PersonRepository extends JpaRepository<Person, Long> {
@Override @PreAuthorize("hasRole('USER')")
Page<Person> findAll(Pageable p);
}
8. Configuring CORS for REST APIs
| Method | Use |
|---|---|
@CrossOrigin on repo |
Per-repository CORS |
RepositoryRestConfigurer.configureCorsRegistry |
Global config |
9. Customizing HAL Response Format
| Property | Default |
|---|---|
spring.data.rest.return-body-on-create |
true |
spring.data.rest.return-body-on-update |
true |
spring.data.rest.detection-strategy |
DEFAULT |
10. Using Search Resources
Example: Expose search endpoint by last name
public interface PersonRepository extends JpaRepository<Person, Long> {
// Exposed at /persons/search/byLastName?lastName=Doe
List<Person> findByLastName(@Param("lastName") String lastName);
}
11. Pagination and Sorting in Data REST
| Param | Effect |
|---|---|
page |
Zero-based page |
size |
Items per page |
sort=field,asc/desc |
Sort spec (multiple) |
HAL _links |
first/prev/next/last |