Repositories

Basic Spring
≈ 2 min read

A repository instead of repetitive EntityManager code

JPA can already save and load entities through EntityManager. But if every service manually implements the same find, save, and delete methods, the data-access layer quickly fills with boilerplate code. Spring Data JPA lets you express that contract as a repository interface.

interface CustomerRepository extends Repository<Customer, Long> {
    Optional<Customer> findById(Long id);

    Customer save(Customer customer);
}

We do not write an implementation class here. Spring Data analyzes the interface when the application starts and creates an object that performs the required operations through JPA. The first generic parameter specifies the entity type, and the second specifies the identifier type.

The repository remains part of the application model

The fact that the framework creates the implementation does not mean the interface should contain every imaginable query. A good repository reflects the operations the application actually needs, while business rules still belong in services and other domain objects.

Under the hood, Spring Data JPA still works with the JPA mechanisms you already know. Entities remain entities, their state is tied to the persistence context, and query execution is ultimately delegated to the JPA provider.

Repository is a data-access abstraction, not a new ORM. To understand saving, relationships, and loading correctly, knowledge of regular JPA is still necessary.