Sub topic 5
Data access with a Spring Data repository
This chapter shows how the BookRepository interface gives the API access to the book table without any implementation code. It assumes you can read Java interfaces and generics, you know basic SQL (select, where, like), and the Book entity from the previous chapter is in place. It also assumes the datasource from the configuration chapter is set up.
What a repository is
A Spring Data repository is an interface you declare. At startup Spring Data creates a proxy object that implements it, and you inject that proxy like any other bean. The proxy translates each method call into a JPA operation, which Hibernate then turns into SQL.
Here is the repository for the book API:
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 primary key (Long). Spring Boot scans for repository interfaces in the package of the main application class and its sub-packages. You do not need @Repository or @EnableJpaRepositories for this to work.
Keep the repository in the same package tree as the application class. A repository placed outside that tree is silently not registered, and the failure appears later as a missing bean for BookRepository.
What you inherit
JpaRepository sits at the bottom of a hierarchy. Each level adds a group of methods.
The diagram below shows that hierarchy.
The methods the service uses most often are these:
| Method | Returns | Behavior |
|---|---|---|
| `save(entity)` | the saved entity | Inserts a new entity or updates an existing one |
| `findById(id)` | `Optional<Book>` | Empty when no row matches |
| `findAll()` | `List<Book>` | Loads every row, so avoid it on large tables |
| `findAll(Pageable)` | `Page<Book>` | Loads one page and runs a count query |
| `existsById(id)` | `boolean` | Checks for a row without loading it |
| `deleteById(id)` | `void` | Deletes the row if it exists and does nothing otherwise |
The first diagram block above is empty on purpose. The real diagram is the second one.
How save decides between insert and update
save is one method for two operations. Spring Data asks whether the entity is new. For an entity with a wrapper-type @Id such as Long, it is new when the id is null.
- A
Bookcreated withnew Book(title, author)has anullid, sosavecallspersist. WithGenerationType.IDENTITY, Hibernate runs theinsertimmediately and fills in the generated id. - A
Bookwith a non-null id that was built by hand is treated as existing, sosavecallsmerge. Hibernate loads the row first, copies the state over, and returns a managed copy.
Always use the value that save returns. After a merge, the object you passed in is not the managed instance, and the returned one is.
Book saved = repository.save(new Book("Dune", "Frank Herbert"));
Long newId = saved.getId(); // populated after the insertThe service from the plan relies on this. create returns BookResponse.from(saved), so the response carries the generated id.
Reading and the Optional contract
findById returns Optional<Book> because a missing row is a normal outcome, not an error. The repository does not throw. The service decides what a missing book means and throws BookNotFoundException. This keeps HTTP out of the data layer.
Book book = repository.findById(id)
.orElseThrow(() -> new BookNotFoundException(id));Do not call Optional.get() without checking. It throws NoSuchElementException, which the exception handler would turn into a 500 response.
Deleting and the existsById check
In Spring Data JPA 3 and later, deleteById does nothing when the id does not exist. Earlier versions threw EmptyResultDataAccessException. If you rely on the older behavior to produce a 404, an upgrade will quietly turn those requests into 204 responses. The service in this tutorial avoids the issue by calling existsById first:
if (!repository.existsById(id)) {
throw new BookNotFoundException(id);
}
repository.deleteById(id);This costs one extra query. A race is possible: another request can delete the row between the check and the delete. For this API that is harmless, because the second delete does nothing.
Derived query methods
When the built-in methods are not enough, you declare a method and Spring Data builds the query from its name. At startup it parses the name into a subject (find...By, exists...By, count...By, delete...By) and a list of conditions on entity properties.
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
List<Book> findByAuthor(String author);
Page<Book> findByAuthorContainingIgnoreCase(String author, Pageable pageable);
Optional<Book> findFirstByTitleOrderByIdAsc(String title);
boolean existsByTitleAndAuthor(String title, String author);
long countByAuthor(String author);
}The common keywords are listed here:
| Keyword in the name | SQL effect |
|---|---|
| `And`, `Or` | Combine conditions |
| `Containing`, `StartingWith`, `EndingWith` | `like` with wildcards added |
| `IgnoreCase` | Case-insensitive comparison |
| `Between`, `GreaterThan`, `LessThan` | Range comparisons |
| `OrderBy...Asc` or `Desc` | Fixed sort order |
| `First`, `Top3` | Limits the number of rows |
The return type controls the result shape:
List<Book>returns every match, possibly empty.Optional<Book>expects zero or one match.Page<Book>with aPageableparameter returns one page and runs a second count query.booleanandlongcome fromexists...andcount...methods.
Names are checked when the application starts. A typo such as findByAuther fails the whole context with a PropertyReferenceException, so you find out immediately and not on the first request.
Writing the query yourself with @Query
Long derived names such as findByAuthorContainingIgnoreCaseAndTitleStartingWithOrderByTitleAsc are hard to read. For anything past two conditions, write the query with @Query. The query is JPQL, which uses entity and property names, not table and column names.
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
@Query("""
select b from Book b
where lower(b.title) like lower(concat('%', :text, '%'))
order by b.title
""")
List<Book> searchByTitle(@Param("text") String text);Use named parameters and bind them with @Param. Never build the JPQL string by concatenating user input, because that opens the query to injection. Bound parameters are always sent as values.
JPQL is also validated at startup, so a wrong property name fails fast here too.
Transactions and the repository
You do not need @Transactional to call a repository method. The base implementation, SimpleJpaRepository, marks its read methods as read-only transactions and its write methods as regular transactions. Each call therefore runs in its own transaction when no outer one exists.
Each repository call being its own transaction becomes a problem when one operation makes several calls. The update method in BookService loads a book and changes its fields. That method works only because the service method is @Transactional, so the entity stays managed and Hibernate saves the change when the transaction commits. Without the annotation, the book would be detached after findById returned, and the setters would change nothing in the database. The transactions chapter covers this in more detail.
Because the configuration sets spring.jpa.open-in-view=false, no session stays open after the service returns. Any lazy association you read outside a transaction throws LazyInitializationException. The Book entity has no associations, so this does not affect it yet.
Common errors
| Symptom | Likely cause |
|---|---|
| `No qualifying bean of type BookRepository` | The interface is outside the scanned package tree |
| `PropertyReferenceException: No property ... found` | A derived method name refers to a property that does not exist |
| `IncorrectResultSizeDataAccessException` | A single-result method matched several rows |
| Updated fields are not saved | The change happened on an entity outside a transaction |
| `Schema-validation: missing table [book]` | `ddl-auto=validate` is set but no migration or `schema.sql` created the table |
| `findAll()` is slow or runs out of memory | The whole table is loaded, so use a `Pageable` overload |
The schema error deserves attention. With ddl-auto=validate, Hibernate only checks that the tables exist. It never creates them. On PostgreSQL, create the table with a migration tool or a script before the first run. The in-memory H2 database from the setup chapter is the exception during development, if you override the property for that profile.
Exercise
A client sends DELETE /api/books/99, but no book with id 99 exists. The service calls only repository.deleteById(99L) with no existence check. What response does the client get on Spring Data JPA 3, and what change makes the API return 404?
Show answer
The client gets 204 No Content, because deleteById does nothing when the row is missing in Spring Data JPA 3 and later, so no exception reaches the controller. Call repository.existsById(id) first and throw BookNotFoundException when it returns false. The exception handler then returns the 404 ProblemDetail.
Exercise
You add the method Optional<Book> findByAuthor(String author) to BookRepository, and the table contains two books by "Ada". What happens when you call it with "Ada", and how would you fix the method?
Show answer
It throws IncorrectResultSizeDataAccessException, because an Optional return type allows at most one result. Change the return type to List<Book>, or use findFirstByAuthorOrderByIdAsc if you want only one book with a defined order.