Sub topic 7
Repository interfaces and what Spring generates
This chapter assumes you can write a JPA entity with @Entity and @Id, that you know what a Spring bean is, and that Spring Boot with Spring Data JPA is already on your classpath. It covers what a repository interface is, which methods you get for free, and what Spring builds at startup so that an interface with no code can talk to a database.
The idea: declare an interface, get an implementation
In plain JPA, every data access class repeats the same work. You inject an EntityManager, then write persist, find and query calls by hand. Spring Data JPA removes that repetition. You write an interface that names the entity and its identifier type. Spring creates the implementation class at runtime and registers it as a bean.
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). That is the whole declaration. You can inject BookRepository into a service by its interface type, and calls like findById and save already work.
The repository hierarchy
Spring Data defines a chain of interfaces. Each one adds methods to the one above it. You pick the one that exposes what you want callers to use.
| Interface | Module | Adds |
|---|---|---|
| `Repository<T, ID>` | Spring Data Commons | Nothing. A marker that lets Spring detect the interface. |
| `CrudRepository<T, ID>` | Spring Data Commons | `save`, `saveAll`, `findById`, `existsById`, `findAll`, `count`, `deleteById`, `delete` |
| `ListCrudRepository<T, ID>` | Spring Data Commons | Same as `CrudRepository`, but `findAll` and `saveAll` return `List` instead of `Iterable` |
| `PagingAndSortingRepository<T, ID>` | Spring Data Commons | `findAll(Sort)` and `findAll(Pageable)` |
| `JpaRepository<T, ID>` | Spring Data JPA | JPA-specific methods such as `flush`, `saveAndFlush`, `deleteAllInBatch`, `getReferenceById` |
JpaRepository extends ListCrudRepository and ListPagingAndSortingRepository, so it includes everything in the rows above it. Most projects extend it directly. The ListCrudRepository and ListPagingAndSortingRepository interfaces exist in Spring Data 3.0 and later. In older versions, findAll returned Iterable in CrudRepository, and JpaRepository overrode it to return List.
Exposing only some methods
Extending JpaRepository exposes every method on it, including bulk deletes. If you want a narrower API, extend Repository and copy only the method signatures you want. Spring matches them by name and parameter types.
import org.springframework.data.repository.Repository;
import java.util.Optional;
public interface ReadOnlyBookRepository extends Repository<Book, Long> {
Optional<Book> findById(Long id);
long count();
}This interface cannot save or delete anything, because those methods are not declared. That is a design choice that keeps write access in one place.
How the CRUD methods behave
The built-in methods have behavior you need to know, because it affects what SQL runs.
save: insert or update
save does not always insert. Spring Data JPA decides whether the entity is new:
- If the identifier is
null(or a primitive with the value 0), the entity is new, andsavecallsEntityManager.persist. - Otherwise,
savecallsEntityManager.merge. Merge loads the row by id first, with aselect, then copies the state of your object onto the managed copy.
This matters in two cases. If you assign identifiers yourself (for example a UUID you create in code), every save looks like an update, so you get an extra select before each insert. If you use @Version, a non-null version field tells Spring the entity is not new, which has the same effect. To control this, implement Persistable<ID> on the entity and report isNew() yourself.
Also note that merge returns a different instance when the argument is detached. Use the return value:
Book saved = books.save(book);findById and getReferenceById
findById runs a query right away and returns an Optional<Book>. It is empty when no row exists.
getReferenceById returns a lazy proxy and does not touch the database. The select happens only when you read a field other than the id. If the row is missing, the exception appears at that later point, as an EntityNotFoundException. This is useful when you only need a reference to set a foreign key, for example book.setAuthor(authors.getReferenceById(authorId)).
delete
deleteById and delete load the entity first so that cascade rules and lifecycle callbacks run. For a large table this is slow. deleteAllInBatch and deleteAllByIdInBatch instead issue a single delete statement and skip cascades and callbacks.
What Spring generates at startup
The implementation is not generated as source code. It is built when the application context starts.
- Detection. Spring Boot's auto-configuration turns on repository scanning. It looks in the package of your
@SpringBootApplicationclass and below it for interfaces that extendRepository. - Factory bean. For each interface found, Spring registers a
JpaRepositoryFactoryBean. The factory bean creates the repository instance when the context needs it. - Proxy. The factory uses a JDK dynamic proxy that implements your interface. Every call on the repository goes through this proxy.
- Target. The proxy forwards CRUD methods to a
SimpleJpaRepositoryinstance. That class is the real implementation ofsave,findByIdand the others, and it holds theEntityManager. - Query methods. For each additional method you declare, Spring builds a query object at startup and routes calls on that method to it. Chapters on derived queries and
@Querycover how those are built. - Interceptors. The proxy adds advice for exception translation and transactions.
The diagram shows a call flowing through these layers.
You can see the real types in a debugger or by printing the class of the injected bean:
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class RepositoryInspection {
@Bean
CommandLineRunner printRepositoryType(BookRepository books) {
return args -> System.out.println(books.getClass());
}
}The output is a proxy class such as jdk.proxy2.$Proxy123, not a class you wrote.
Transactions and exceptions on repositories
Each CRUD method on SimpleJpaRepository is transactional. Read methods use @Transactional(readOnly = true). Write methods such as save and delete use a plain @Transactional. If your service method already has a transaction, repository calls join it. If it does not, each repository call runs in its own short transaction.
This has a consequence. Without a surrounding transaction, books.findById(1L) returns an entity that is detached as soon as the call ends, because its transaction and persistence context are gone. Lazy associations on it cannot be loaded later. Putting @Transactional on the service method keeps one persistence context open for the whole method.
Your own query methods on the interface do not get @Transactional automatically unless the interface declares it. You can place @Transactional(readOnly = true) on the interface or on single methods to set a default.
Exceptions are also translated. A PersistenceException or a Hibernate exception thrown inside the repository is converted into Spring's DataAccessException hierarchy. For example, a unique-key violation arrives as DataIntegrityViolationException, so service code does not depend on Hibernate types.
Adding your own implementation
Sometimes a query cannot be expressed with a method name or @Query. You can add code to a repository using a fragment.
- Define a fragment interface with the extra method.
- Write a class that implements it. The class name must be the fragment interface name followed by
Impl. - Make the repository extend the fragment interface.
import java.util.List;
public interface BookRepositoryCustom {
List<Book> findOldestPerAuthor();
}import jakarta.persistence.EntityManager;
import java.util.List;
class BookRepositoryCustomImpl implements BookRepositoryCustom {
private final EntityManager em;
BookRepositoryCustomImpl(EntityManager em) {
this.em = em;
}
@Override
public List<Book> findOldestPerAuthor() {
return em.createQuery(
"select b from Book b where b.publishedYear = "
+ "(select min(b2.publishedYear) from Book b2 where b2.author = b.author)",
Book.class).getResultList();
}
}import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long>, BookRepositoryCustom {
}The proxy sends findOldestPerAuthor to BookRepositoryCustomImpl, and everything else to SimpleJpaRepository. The EntityManager you inject here is a shared proxy that joins the current transaction. Because the implementation is your own code, it does not get automatic transaction or exception handling unless you add @Transactional to it.
Common errors
NoSuchBeanDefinitionExceptionfor the repository. The interface sits outside the package scanned from your main class. Move it, or add@EnableJpaRepositories(basePackages = "...").No property xyz found for type Book. A method name refers to a field the entity does not have. Spring checks every declared method at startup, so the application fails to start rather than failing at the first call.Not a managed type. The entity class is not found by entity scanning. Check the package or add@EntityScan.LazyInitializationException. You read a lazy association after the repository call returned and the transaction ended. Keep the work inside a service transaction, or fetch the association in the query.- Extra
selectbefore an insert. The entity has an assigned identifier or a version value, sosavechosemerge. UsePersistableor let the database generate the id.
Summary of choices
| Need | Use |
|---|---|
| Standard CRUD, paging, JPA extras | Extend `JpaRepository` |
| Restricted set of operations | Extend `Repository` and copy the signatures |
| Reference for a foreign key, no select | `getReferenceById` |
| Delete many rows with one statement | `deleteAllInBatch` |
| Logic that no query method can express | A fragment interface with an `Impl` class |
Exercise
A service calls books.save(book) where Book has an id of type Long that your code sets to a fixed value, such as 42, before saving. The row does not exist yet. What SQL does Hibernate run, and how can you avoid the extra statement?
Show answer
Because the id is not null, Spring Data JPA treats the entity as not new and calls merge. Hibernate first runs a select for id 42, finds nothing, and then runs the insert. To avoid the extra select, make the entity implement Persistable<Long> and return true from isNew() for entities that have not been stored yet (for example with a transient boolean flag), or let the database generate the id so it is null on first save.
Exercise
A repository method findById returns a Book. Later, outside any transaction, your code calls book.getAuthor().getName() and gets a LazyInitializationException. Why does this happen when findById itself worked, and name two ways to fix it?
Show answer
Without an outer transaction, findById runs in its own short transaction. When the call returns, the persistence context closes and the entity is detached. author is a lazy proxy, and a detached proxy cannot load its data. Fixes: put @Transactional on the calling service method so the persistence context stays open, or fetch the author in the query with join fetch or @EntityGraph.
Exercise
What is the difference between deleteById and deleteAllByIdInBatch, and when would you choose the second one?
Show answer
deleteById loads the entity and removes it through the persistence context, so cascades and lifecycle callbacks run. deleteAllByIdInBatch sends one delete ... where id in (...) statement and skips cascades, callbacks and the persistence context. Choose it for large deletes of rows that have no cascade rules or callbacks you depend on.