skip to content

Spring Data REST

Exposing repositories directly as hypermedia REST resources, with HAL representations, projections and excerpts, and control over what is exported. Interviewers usually ask whether that is a good idea, which is the real question.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

questions

11

What is HAL, and what do the _links and _embedded properties in a Spring Data REST response mean?

level: juniorimportance: must knowfreq 62%

answer

  1. application/hal+json default
  2. _links = rels + hrefs (self)
  3. _embedded = inlined collection/related
  4. EntityModel/CollectionModel/PagedModel
  5. page block + first/next/prev/last

basics

~10 s

HAL (Hypertext Application Language) is the default JSON format Spring Data REST returns. _links holds URLs to related resources (like self), and _embedded holds the actual related or collection data inline.

solid answer

~30 s

HAL is a hypermedia JSON convention (media type application/hal+json) that Spring Data REST uses by default. Every resource carries a _links object mapping link relations (rel names like self, or an association name) to hrefs, so clients navigate by following links instead of hardcoding URLs. Collections and related resources are placed under _embedded, keyed by the relation name (usually the pluralised entity name), each item again carrying its own _links. Spring HATEOAS builds these representations via EntityModel, CollectionModel, and PagedModel; paged responses also add a page object (size, totalElements, number) plus first/next/prev/last navigation links. This makes the API self-describing and discoverable.

code

java · 11 lines
java
@Entity
public class Book {
    @Id @GeneratedValue Long id;
    String title;
    @ManyToOne Author author; // becomes an 'author' link, not inlined
}

@RepositoryRestResource
public interface BookRepository extends JpaRepository<Book, Long> { }
// GET /books -> _embedded.books[*] each with _links.self + _links.author,
// plus top-level _links + page metadata.

go deeper

for a junior

Must know HAL is the default, and that _links = navigation, _embedded = inlined data.

for a middle

Should explain EntityModel/CollectionModel/PagedModel and the page metadata block.

for a senior

Should discuss id exposure, @Relation renaming, and association links being lazy references.

for a principal

Frames HAL as a discoverability contract and weighs it against HAL-FORMS and client coupling concerns.

**HAL** stands for *Hypertext Application Language* — a simple convention for embedding hyperlinks and related data into JSON. Its media type is `application/hal+json`, and it is the **default output format of Spring Data REST**. The goal is HATEOAS (Hypermedia As The Engine Of Application State): responses tell the client where it can go next via links, rather than the client hardcoding URL patterns. **The two reserved properties:** - **`_links`** — an object whose keys are *link relations* (`rel`) and whose values contain an `href`. Every resource has at least a `self` link (its canonical URL). For each JPA association on the entity, Spring Data REST adds a link named after that association, whose href points to a sub-resource you can follow to load the related entity/entities. Example: a `Book` resource exposes `self` and `author` links. - **`_embedded`** — an object holding *inlined* resource data so the client does not have to make another request. For a **collection** endpoint (e.g. `GET /books`), the actual list lives under `_embedded.books` (the key is the relation name, normally the pluralised, lower-cased entity name; customisable with `@Relation`). Each embedded item is itself a full HAL resource with its own `_links.self`. **Who builds this:** Spring Data REST delegates to **Spring HATEOAS**, whose representation model classes are `EntityModel<T>` (single item + links), `CollectionModel<T>` (list + links), and `PagedModel<T>` (adds a `page` metadata block). The serializer for HAL is `Jackson2HalModule`. **Paging:** When a repository returns a `Page`, the HAL body includes a top-level `page` object with `size`, `totalElements`, `totalPages`, and `number`, plus `_links` for `first`, `prev`, `next`, and `last` when applicable. **Example shape of `GET /books`:** ```json { "_embedded": { "books": [ { "title": "Dune", "_links": { "self": {"href": "/books/1"}, "author": {"href": "/books/1/author"} } } ] }, "_links": { "self": {"href": "/books?page=0&size=20"}, "profile": {"href": "/profile/books"} }, "page": { "size": 20, "totalElements": 1, "totalPages": 1, "number": 0 } } ``` **Common gotchas:** - The `href` for associations is a *link to follow*, not the embedded object — the association is lazy by default and not inlined unless you use a projection/excerpt. - The `profile` link points to ALPS/JSON-Schema metadata describing the resource, generated automatically. - Entity `id` fields are *not* serialised into the JSON body by default — the identity is expressed through the `self` link's href. You can force ids to appear with `RepositoryRestConfiguration.exposeIdsFor(...)`. **When to use HAL:** it is the sensible default for a hypermedia REST API where clients discover capabilities dynamically. If you need affordance metadata (which HTTP methods and fields are valid), step up to HAL-FORMS.

  • Why doesn't the entity's numeric id appear in the JSON body by default?
    Spring Data REST expresses identity through the self link's href, keeping the payload URL-driven. You can override this with RepositoryRestConfiguration.exposeIdsFor(Book.class) in a RepositoryRestConfigurer.
  • Under what key does a collection endpoint place its items, and how do you change it?
    Under _embedded keyed by the pluralised, lower-cased entity name (e.g. _embedded.books). Change it by annotating the entity with @Relation(collectionRelation = "...").

saying these in an interview costs you the question

  • Thinking _embedded always inlines related entities (associations are links unless a projection/excerpt embeds them)
  • Believing the id field is always in the JSON body
  • Confusing _links.self with a link to a different resource

context

open as a page

What does Spring Data REST do with your repositories, and what role does @RepositoryRestResource play?

level: juniorimportance: must knowfreq 55%

basics

~10 s

Spring Data REST automatically turns each Spring Data repository into a REST API with hypermedia (HAL) links — CRUD endpoints appear with no controller code. @RepositoryRestResource customizes that exposure, e.g. changing the URL path.

open as a page

How do @Projection interfaces and an excerptProjection change the exposed representation in Spring Data REST?

level: middleimportance: must knowfreq 55%

basics

~10 s

A @Projection is an interface selecting/reshaping which fields a resource exposes. You request it with ?projection=name. Setting it as excerptProjection on the repository makes it the default view for items inside collections (_embedded).

open as a page

What does exported=false do at the repository, query-method, and association level, and what is the gotcha when you hide a repository that backs an association?

level: middleimportance: should knowfreq 42%

basics

~20 s

exported=false stops Spring Data REST from publishing something over HTTP while keeping it as a normal Spring bean. On a repository it hides all its endpoints; on a query method it hides that finder; on an association it drops the association resource. Gotcha: hiding a repository can break linking to its entities.

open as a page

How do @RepositoryRestResource and @RestResource change the URL path and HAL link relation of an exposed resource, and how do path and rel differ?

level: middleimportance: should knowfreq 40%

basics

~20 s

path sets the URL segment (e.g. /members); rel sets the name of the link in the HAL _links output that clients follow. @RepositoryRestResource customizes the whole collection; @RestResource customizes a single query method or association.

open as a page

What is RepositoryRestConfigurer and what representation-level settings can you customise with it?

level: seniorimportance: should knowfreq 48%

basics

~10 s

RepositoryRestConfigurer is a callback interface you implement (as a @Component) to customise Spring Data REST: base path, default media type, whether entity ids are exposed, projections, Jackson mapper, CORS, and HTTP method exposure.

open as a page

How does HAL-FORMS differ from plain HAL, and how do you enable it in Spring Data REST?

level: seniorimportance: should knowfreq 35%

basics

~20 s

HAL-FORMS extends HAL by adding a _templates section describing how to write (which HTTP method, which fields, required/read-only). You enable it by content negotiation (Accept: application/prs.hal-forms+json) or by setting it as the default media type.

open as a page

What is RepositoryDetectionStrategy in Spring Data REST, what are its modes, and how do you configure it?

level: seniorimportance: should knowfreq 33%

basics

~20 s

RepositoryDetectionStrategy decides which repositories Spring Data REST exposes. Modes: DEFAULT (all public repos, respecting exported=false), ALL (every repo, ignoring visibility and annotations), ANNOTATED (only repos annotated for export), and VISIBILITY (only public repos). Set it via the spring.data.rest.detection-strategy property or a RepositoryRestConfigurer.

open as a page

How does Spring Data REST expose derived query (search) methods, and how do you control their paths and parameters?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Derived finder methods like findByLastName are exposed under /{repo}/search. Each method becomes /{repo}/search/{name} with its parameters as query params. Use @Param to name the query parameters, @RestResource(path/rel) to rename the endpoint, and exported=false to hide a finder.

open as a page

You expose repositories via Spring Data REST with excerpt projections and HAL. What representation-level pitfalls should you anticipate at scale, and how do you mitigate them?

level: principalimportance: nice to knowfreq 22%

basics

~20 s

Watch for excerpt projections that inline heavy associations causing over-fetch/N+1 on large collections, open projections defeating column optimisation, clients coupling to auto-generated URLs, and exposing internal fields. Mitigate with closed projections, method exposure limits, and careful excerpt scope.

open as a page

What are the architectural and security trade-offs of auto-exposing repositories with Spring Data REST, and when would you choose it over hand-written controllers?

level: principalimportance: nice to knowfreq 24%

basics

~20 s

Auto-exposure is fast but tightly couples your HTTP API to your persistence model and exposes everything by default, which is a security and contract risk. Use it for internal/admin CRUD; prefer DTO-based controllers when you need a stable public contract, custom validation, or business logic.

open as a page