Mastering Spring Data REST: Quick Guide to Auto-Generated CRUD APIs
This article explains how Spring Data REST automatically exposes Spring Data repositories as RESTful endpoints, covering setup, entity and repository definitions, exposure strategies, custom base paths, CRUD operations, field projection, event handling, and visual tools for Spring Boot 3.0.5 with JDK 17.
1. Introduction
Spring Data REST, part of the Spring Data project, automatically exposes Spring Data repositories as RESTful HTTP endpoints, allowing entities from JPA, MongoDB and other stores to be published as resources, dramatically reducing boilerplate CRUD code.
2. Practical Example
2.1 Dependency Management
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>2.2 Entities & Repository
@Table(name = "t_users")
@Entity
public class Users {
@Id
private String id;
private String username;
private String password;
private int enabled;
private int locked;
}
@Entity
@Table(name = "t_order")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String sno;
private BigDecimal amount;
} public interface UsersRepository extends JpaRepository<Users, String>, JpaSpecificationExecutor<Users> {}
public interface OrderRepository extends JpaRepository<Order, Long>, JpaSpecificationExecutor<Order> {}By default Spring Data REST serves resources under the root URI "/". Accessing /profile lists all repositories, and /profile/orders shows the Order configuration.
2.3 Exposure Strategy
DEFAULT : Expose all public repositories, respecting @RestResource export flag.
ALL : Expose every repository regardless of visibility.
ANNOTATED : Only repositories annotated with @RepositoryRestResource are exposed unless export=false.
VISIBILITY : Only public repositories with explicit annotations are exposed.
Configure a different strategy in application.yml:
spring:
data:
rest:
detection-strategy: annotatedAdding @RestResource to UsersRepository limits exposure to the Users entity only.
@RestResource
public interface UsersRepository extends JpaRepository<Users, String>, JpaSpecificationExecutor<Users> {}2.4 Custom Base URI
Change the default root path from "/" to "/api" via configuration:
spring:
data:
rest:
basePath: /apiOr programmatically:
@Component
public class CustomizedRestMvcConfiguration implements RepositoryRestConfigurer {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) {
config.setBasePath("/api");
}
}2.5 CRUD Operations
Create : POST to the collection URI returns HTTP 201 with Location header pointing to the new resource.
Update : PUT to the resource URI updates the entity.
Delete : DELETE to the resource URI removes it.
Read / List : GET the collection URI (e.g., /api/orders?page=0&size=20) returns a paginated list; sorting is added via sort=propertyName,asc|desc.
2.6 HEAD Request
Sending a HEAD request to a resource returns HTTP 204 if the resource exists, without a body.
2.7 Controlling Field Visibility
Use projections to hide fields, e.g.:
@Projection(name = "noAddress", types = { Order.class })
public interface NoAddress {
BigDecimal getAmount();
String getSno();
}Or apply @JsonIgnore on a field:
@JsonIgnore
private String password;2.8 Repository Events
Spring Data REST fires eight events during entity lifecycle. Example handler using annotations:
@Component
@RepositoryEventHandler
public class DomainObjectEventHandler {
@HandleBeforeCreate
public void handleBeforeCreate(Order order) {
System.out.println("Creating order..." + order);
}
@HandleBeforeSave
public void handleBeforeSave(Order order) {
System.out.println("Saving order..." + order);
}
}Alternatively extend AbstractRepositoryEventListener to override methods.
@Component
public class DomainObjectEventListener extends AbstractRepositoryEventListener<Order> {
@Override
protected void onBeforeCreate(Order entity) {
System.out.println("onBeforeCreate...");
}
@Override
protected void onBeforeSave(Order entity) {
System.out.println("onBeforeSave...");
}
}2.9 Visual Explorer
Add the HAL Explorer dependency to enable a web UI for navigating the REST resources.
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-hal-explorer</artifactId>
</dependency>Visit /api to see the explorer UI, where you can browse, add, edit, and delete resources.
This concludes the guide; the examples demonstrate how Spring Data REST simplifies building RESTful services with Spring Boot.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
