Stage 3 - Repositories: JpaRepository and Basic Data Access
Repository Pattern gives the service a data-access interface and hides repetitive persistence operations. A service should express a business operation, not repeat SQL or EntityManager calls for every basic action. A repository gives the service a clear interface for storing, loading, counting, and deleting entities.

What JpaRepository provides
Spring Data JPA creates repository implementations at runtime. You declare an interface, extend JpaRepository, and specify the entity type and id type. There is no class to implement for common operations.
public interface UserRepository extends JpaRepository<User, Long> {
}
User is the entity. Long is the type of its primary key. From this small interface, Spring Data provides methods such as save, findById, findAll, delete, deleteById, count, pagination methods, sorting methods, and query creation from method names.
The repository is usually injected into a service. This keeps controllers thin and prevents database access code from spreading across the web layer. The service decides what the operation means; the repository performs persistence.
Main methods
save() stores an entity. For a new entity, Hibernate creates an insert. For an existing managed or merged entity, it may create an update. The method name is intentionally broad because JPA decides whether the object is new based on its identifier and persistence state.
findById() searches by primary key and returns Optional<T>. It does not return null because absence is an expected result, not a technical failure. The caller must handle both cases: entity exists or entity does not exist.
findAll() returns all rows for the entity table. It is useful for demos and small reference tables, but it can be dangerous for large production tables. For real screens and APIs, prefer pagination with Pageable.
delete() removes a specific entity. deleteById() removes by primary key. count() returns the number of rows. These methods are simple, but they still execute SQL and should be used with transaction boundaries and data size in mind.
| Repository call in service code | What the service must decide before calling it | What SQL work is hidden behind the method |
|---|---|---|
save(entity) |
Is this object valid, and is the use case create or update? | Hibernate chooses insert for a new entity or update for an existing one. |
findById(id) |
What should happen if this id is absent? | A select ... where id = ? is executed and the result is wrapped in Optional. |
findAll() |
Is the table small enough to load fully? | A full table query is executed; this can be dangerous without pagination. |
delete(entity) |
Is deletion allowed by business rules? | Hibernate schedules a delete for the entity primary key. |
count() |
Is an exact count needed for this screen or rule? | The database executes select count(*), which can still be expensive on large data. |
Optional and missing data
Optional is a container that may hold a value or may be empty. findById returns Optional because a requested id may not exist. This forces the developer to make a decision: return a 404 response, throw a domain exception, or use a fallback.
public User getUser(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new EntityNotFoundException("User not found: " + id));
}
Do not call .get() on Optional without checking it. That only moves the error to a less clear place. A service method should translate missing data into a meaningful application behavior.
Glossary
- ORM
- Object-Relational Mapping, a technique that maps objects in code to relational database tables.
- JDBC
- The standard Java API for connecting to databases and executing SQL.
- entity
- A Java class mapped to a database table and managed by JPA as persistent data.
- persistence context
- The JPA runtime area that tracks managed entities and synchronizes them with the database.
- repository
- A data access abstraction that hides database operations behind methods such as save, find, and delete.
- JpaRepository
- A Spring Data JPA interface that provides common repository operations for an entity.
- CRUD
- The basic data operations create, read, update, and delete.
- DTO
- A Data Transfer Object used to carry data between layers or across an API boundary.
- projection
- A reduced or custom view of data selected from a larger entity or query result.
- JPQL
- A JPA query language that queries entities and fields instead of raw tables and columns.
- derived query
- A Spring Data query generated from a repository method name.
- lazy loading
- Loading related data only when it is first accessed.
- eager loading
- Loading related data immediately together with the main object.
- cascade
- A persistence rule that propagates an operation from one entity to related entities.
- orphan removal
- A JPA rule that deletes a child entity when it is removed from its parent relationship.
- transactional
- Describes code that runs inside a transaction boundary.
- rollback
- Cancelling a transaction so its database changes are not committed.
- propagation
- A transaction setting that defines how a method joins, creates, or rejects a transaction.