Sub topic 5
Data access with a Spring Data repository
This chapter assumes you have a working Book entity, a configured datasource, and basic knowledge of Java interfaces and generics. You need to know what a JPA entity is, but not how Hibernate works internally.
What a repository gives you
A Spring Data repository is an interface that you declare and Spring implements for you. You write no SQL and no implementation class for the standard operations. Extend JpaRepository and give it the entity type and the type of its primary key:
public interface BookRepository extends JpaRepository<Book, Long> {
}This empty interface is enough for the CRUD API in this tutorial. It inherits these methods:
| Method | Behavior |
|---|---|
| `save(entity)` | Inserts a new entity or updates an existing one |
| `findById(id)` | Returns an `Optional<Book>` |
| `findAll(Pageable)` | Returns a `Page<Book>` |
| `existsById(id)` | Returns `true` if a row with that key exists |
| `deleteById(id)` | Removes the row |
How it works at runtime
At startup, Spring Data scans for interfaces that extend a repository type. For each one it creates a proxy, which is a generated object that implements the interface. The proxy delegates the inherited methods to a shared class named SimpleJpaRepository, which uses the JPA EntityManager. You then inject BookRepository like any other bean.
Adding your own queries
When you need a lookup that the base interface does not offer, declare a method. Spring Data builds the query from the method name:
public interface BookRepository extends JpaRepository<Book, Long> {
List<Book> findByAuthor(String author);
boolean existsByTitleAndAuthor(String title, String author);
Page<Book> findByAuthorContainingIgnoreCase(String author, Pageable pageable);
}The name is parsed at startup. findBy starts a query, Author refers to the entity field author, and keywords such as And, Containing, and IgnoreCase refine it. A method can also take a Pageable and return a Page, which is how you page through results. Chapter 13 covers that in detail.
If the name becomes unwieldy, write the query yourself with @Query and a JPQL string. JPQL is a query language that uses entity and field names instead of table and column names.
Common errors
No property 'titel' found for type 'Book'. A derived method refers to a field that does not exist. The application fails at startup, not on the first call, so typos surface quickly.Not a managed type: class Book. The entity is outside the packages that Spring Boot scans. Keep it in or below the package of the@SpringBootApplicationclass.Schema-validation: missing table [book]. Withddl-auto=validate, Hibernate checks the schema but never creates it. Create the table yourself, for example with a migration tool, or use H2 in development.- Calling
.get()onfindByIdwithout checking.findByIdreturns anOptional. Handle the empty case withorElseThrow, as the service does, and not with a bareget(). - Assuming
savealways inserts. If the entity has anullid,saveinserts. If the id is set and the row exists, it updates. This matters because the service relies on this behavior, and on dirty checking inside a transaction, for updates.
Keep the repository thin
A repository should only describe data access. Checks such as "does this book exist before deleting" and the conversion to DTOs belong in the service. This keeps the repository easy to replace with a mock in tests.
Exercise
You add the method List<Book> findByWriter(String writer) to BookRepository, but the Book entity has fields named title and author. When does the error appear, and how do you fix it?
Show answer
The application fails at startup, because Spring Data parses derived method names when it creates the repository proxy. The error says that no property writer was found for type Book. Rename the method to findByAuthor, or write the query with @Query if you want to keep a different name.