liveBook · Manning

Repository pattern

As explained in Spring Start Here, Second Edition

A repository is an abstraction that provides access to stored application data.

A repository manages data persistence: it gives application logic a place to store and retrieve data without taking on database access itself. Defining a repository as an interface separates that responsibility from its implementation, so the implementation can change without changing the service that uses it. section 4.1.3 section 4.3

Publishing a comment

A CommentService publishes a comment by asking CommentRepository to store it and a notification proxy to send it. The service depends on interfaces; DBCommentRepository supplies the storage implementation. In Spring, @Repository marks the repository component and makes its role visible. section 4.1.3 section 4.3

Figure 4.6 The CommentService object depends on the abstractions provided by CommentRepository and CommentNotificationProxy interfaces. The classes DBCommentRepository and EmailCommentNotificationProxy further implement these interfaces. This design decouples the implementation of the “publish comment” use case from its dependencies and makes the application easier to change for future developments.

The diagram shows how repository and notification interfaces separate the service from replaceable implementations. section 4.1.3

Spring Data takes this further: declare repository interfaces and let the framework provide implementations at runtime. Contracts such as CrudRepository supply common operations; methods can also define custom queries with @Query or derive them from method names. section 14.0 section 14.5

How Spring Start Here, Second Edition covers it

How deep it goes
Builds from a hand-written interface and implementation to Spring Data contracts, query methods, and startup validation rules.
Examples
Uses comment storage, DBCommentRepository, @Repository, and Spring Data interfaces with CRUD and custom query operations.
What it assumes
Assumes familiarity with abstractions and dependency injection when connecting repository interfaces to Spring-managed components.
What you can do after
Apply it via Spring Data interfaces to implement data operations without writing routine database access code by hand.
How it connects
Connects repositories to services, dependency injection, data access objects, Spring Data, and persistence layers.

Also explained in

Compare how 11 books explain repository pattern →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.