Sub topic 7
Repository interfaces and what Spring generates
This chapter assumes you can write a JPA entity with @Entity and @Id, and that you have a Spring Boot project with spring-boot-starter-data-jpa and a configured database. You should also know what dependency injection is.
The idea
A repository is an object that stores and retrieves entities. In Spring Data JPA you do not write its implementation. You declare an interface, and Spring creates a class that implements it when the application starts.
Here is the repository for the Book entity:
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
}The two type arguments are the entity type (Book) and the type of its @Id field (Long). The interface has no methods of its own, yet it already supports saving, loading and deleting books.
What Spring generates
At startup, Spring Boot scans for interfaces that extend a Spring Data repository type. For each one it builds a proxy, which is a generated object that implements the interface. The proxy forwards the standard methods to SimpleJpaRepository, a class that ships with Spring Data JPA and uses an EntityManager internally. For query methods you declare yourself, the proxy builds a query from the method definition (later chapters cover this).
Because the proxy is a Spring bean, you inject it like any other:
import org.springframework.stereotype.Service;
@Service
public class CatalogService {
private final BookRepository books;
public CatalogService(BookRepository books) {
this.books = books;
}
}The repository hierarchy
Each interface in the hierarchy adds methods to the one before it. Pick the smallest one that meets your needs.
| Interface | Adds |
|---|---|
| `Repository` | Nothing. A marker that lets you declare only the methods you want. |
| `CrudRepository` | `save`, `findById`, `findAll`, `count`, `existsById`, `deleteById`, `delete` |
| `PagingAndSortingRepository` | `findAll(Sort)` and `findAll(Pageable)` |
| `JpaRepository` | `flush`, `saveAndFlush`, `saveAllAndFlush`, `deleteAllInBatch`, and `findAll` that returns a `List` |
JpaRepository is the usual choice. If you want to expose a narrower API, for example a read-only repository, extend Repository and copy only the signatures you need.
Using the CRUD methods
Book saved = books.save(new Book("Dune", 1965)); // insert
Optional<Book> found = books.findById(saved.getId()); // select by id
boolean exists = books.existsById(saved.getId());
books.delete(saved); // deleteTwo behaviours cause common mistakes:
savedecides between insert and update by checking whether the entity is new. An entity with anullid (or, with a@Versionfield, anullversion) is treated as new and persisted. Otherwise Spring callsmerge. Always use the returned instance, becausemergecan return a different object than the one you passed in.findByIdreturns anOptional. It does not returnnull. UseorElseThrow()when the entity must exist.
Common errors
- No qualifying bean of type
BookRepository. The interface is outside the packages Spring Boot scans, which start at your@SpringBootApplicationclass. Move it, or add@EnableJpaRepositories(basePackages = "..."). - Not a managed type. The entity is outside the entity scan. Move it, or add
@EntityScan. - Wrong id type. If the second type argument does not match the
@Idfield, lookups fail at runtime or at startup. - Adding
@Repositoryor an implementing class by hand. Neither is needed for a generated repository.
Exercise
You call Book saved = books.save(book) where book already has an id and exists in the database. Which EntityManager operation does Spring Data use, and why should you keep using saved afterwards?
Show answer
Because the entity is not new, save calls merge. merge copies the state onto a managed instance and returns it, and that instance can be a different object from book. Using saved makes sure you work with the managed instance.
Exercise
You want a repository that exposes only findById and save to callers. Which interface do you extend, and what do you declare?
Show answer
Extend Repository<Book, Long> and declare Optional<Book> findById(Long id); and Book save(Book book);. Spring Data matches these signatures to the implementations in SimpleJpaRepository.