Sub topic 2
Repository Interfaces and What Spring Generates
Assume you know Java interfaces, Spring dependency injection, basic SQL, and that Book is a JPA entity with title, publishedYear, and author.
Repository interfaces
A repository is a Spring-managed object for reading and writing entities. Extend a Spring Data interface instead of implementing common database operations yourself.
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.*;
import java.util.List;
public interface BookRepository extends JpaRepository<Book, Long> {
List<Book> findByTitleContainingIgnoreCase(String text);
Page<Book> findByPublishedYearGreaterThanEqual(
int year, Pageable pageable);
@Query("select b from Book b join fetch b.author " +
"where b.publishedYear = :year")
List<Book> findByYearWithAuthor(@Param("year") int year);
}JpaRepository<Book, Long> says that this repository manages Book entities whose identifier type is Long. Spring creates a proxy implementation at startup and injects it wherever BookRepository is required.
| Method | What Spring provides |
|---|---|
| `save(book)` | Insert or update a `Book` |
| `findById(id)` | Find one book by identifier |
| `findAll()` | Load all books |
| `delete(book)` | Delete a book |
Derived query methods
Spring parses a method name and builds a query from it. findByTitleContainingIgnoreCase searches for a title containing the supplied text without case sensitivity. GreaterThanEqual becomes a >= comparison.
Use clear method names. A typo or unsupported property name causes an application startup error. Derived queries are convenient for simple conditions, but long names become difficult to review.
Custom queries with `@Query`
Use JPQL when the query needs joins or logic that a method name cannot express. JPQL uses entity and field names, not table and column names. The join fetch in the example loads each author with the book and can prevent extra author queries.
For database-specific SQL, set nativeQuery = true:
@Query(value = "select * from books where published_year >= :year",
nativeQuery = true)
List<Book> findRecentBooks(@Param("year") int year);Use named parameters and bind them with @Param; do not concatenate user input into SQL.
Pagination and sorting
A Pageable carries the page number, page size, and sort order. A Page<Book> includes the current results and metadata such as total pages. For example, PageRequest.of(0, 20, Sort.by("title")) requests the first 20 books ordered by title.
Exercise
Which query does findByPublishedYearGreaterThanEqual(int year, Pageable page) represent?
Show answer
It finds books whose publishedYear is greater than or equal to year, returning one requested page.