Логотип Workflow

Article

Updated at:

Repositories

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.

Repository pattern in Spring Data JPA

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 codeWhat the service must decide before calling itWhat 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.

Practice

Create UserRepository extends JpaRepository<User, Long> and ProductRepository extends JpaRepository<Product, Long>. Write a service method that creates a user, another method that loads by id, and a third method that returns a paginated list of products. Enable SQL logging and compare repository calls with generated SQL. Notice that the repository removes boilerplate, but it does not remove the need to understand what query is executed.

Understanding checklist

  • I can explain why repositories are used instead of direct database code in controllers.
  • I know what JpaRepository<User, Long> means.
  • I can describe save, findById, findAll, delete, and count.
  • I understand why findById returns Optional.
  • I know when findAll is risky and why pagination matters.

Please login to pass quizzes.

Practice

Interactive practice

Complete tasks and check your answer instantly.