Repositories you don't implement, queries derived from method names, and how Spring Boot wires it all up.
@Query for explicit JPQL / native SQL.
Add spring-boot-starter-data-jpa and a JDBC driver. Boot then auto-configures the
DataSource, the EntityManagerFactory (Hibernate by default), a
JpaTransactionManager, and enables repositories — you write almost no plumbing.
@Entity
public class Account {
@Id @GeneratedValue
private Long id;
private String email;
// ...
}
Configure the database in application.properties (spring.datasource.url/username/password).
With H2 on the classpath and no URL, Boot even spins up an in-memory database automatically.
| Interface | Adds |
|---|---|
Repository<T,ID> | Marker interface — no methods |
CrudRepository | save, findById, findAll, delete, count, existsById |
PagingAndSortingRepository | findAll(Pageable), findAll(Sort) — paging & sorting |
JpaRepository | JPA extras: flush, saveAll, findAll returning List, batch deletes |
Each extends the one above it, so JpaRepository has everything.
@Repository annotation, no implementing class.
public interface AccountRepository extends JpaRepository<Account, Long> {
// derived queries — no body needed:
List<Account> findByEmail(String email);
List<Account> findByActiveTrueOrderByEmailAsc();
}
Spring parses the method name into a query. The name = a prefix + By + property
conditions:
| Part | Options |
|---|---|
| Prefix | find…By, read…By, get…By, query…By, count…By, exists…By, delete…By |
| Conditions | And, Or, Between, LessThan, GreaterThan, Like, StartingWith, In, IsNull, True/False, IgnoreCase |
| Ordering | OrderBy<Property>Asc / Desc |
| Return types | the entity, Optional<T>, List<T>, Page<T>, Stream<T>, long (for count) |
Examples: findByLastName(String), findByAgeGreaterThan(int),
findByLastNameAndFirstName(...), countByActiveTrue().
@QueryWhen a derived name would be unwieldy, write the query yourself. JPQL by default; native SQL with a flag:
@Query("select a from Account a where a.email = :email")
Account lookup(@Param("email") String email); // JPQL + named param
@Query(value = "select * from account where email = ?1", nativeQuery = true)
Account lookupNative(String email); // native SQL
Read "Core concepts", "Defining Query Methods", and the "Query Creation" keyword table.
Derived-query validity and the repository hierarchy are the money questions. Covers your book's whole Spring Data JPA section. Options shuffle on every load.
JpaRepository
and CrudRepository in practice? Ask. Say "continue" to start Section 3 — Spring MVC
with Lesson 11.