Cheatsheet

Spring Data JPA

Key idea

With Spring Data JPA you declare an interface extending `JpaRepository<Entity, Id>` and Spring generates the implementation at runtime: CRUD, paging, queries derived from the method name and `@Query` queries. Underneath, JPA (Hibernate) maps entities to tables and the `EntityManager` tracks them within each transaction.

Diagram (UML)

ApplicationContextAthleteAthleteControllerAthleteServiceAthleteRepository (proxy)SimpleJpaRepository@Entity AthleteEntityManagerH2

Key pieces

  • @Entity, @Id, @GeneratedValue, @Column, @OneToMany/@ManyToOne
  • Repository → CrudRepository/ListCrudRepository → PagingAndSortingRepository → JpaRepository
  • Derived queries: findBy…, countBy…, existsBy…, deleteBy…, findTop3By…OrderBy…, IgnoreCase, Containing, Between…
  • @Query (JPQL or nativeQuery = true) + @Param; @Modifying for UPDATE/DELETE
  • Pageable, PageRequest.of(page, size, Sort), Page<T>, Sort
  • @DataJpaTest and TestEntityManager to test the persistence layer

AthleteRepository.java

Optional<Athlete> findByName(String name);                       // where name = ?

List<Athlete> findByDivisionOrderByNameAsc(String division);     // where division = ? order by name

long countByDivision(String division);

boolean existsByNameIgnoreCase(String name);

List<Athlete> findByNameContainingIgnoreCase(String fragment);  // like %fragment%

Remember for the exam

  • The repository is a generated (JDK) proxy whose work is done by SimpleJpaRepository
  • findById returns Optional<T>; save inserts if new and merges otherwise
  • SimpleJpaRepository's methods are already @Transactional (read ones, readOnly = true)
  • An entity read inside a transaction is managed: its changes are saved on commit (dirty checking), without calling save
  • Spring Boot auto-configures the DataSource, EntityManagerFactory and JpaTransactionManager, and scans entities and repositories from the @SpringBootApplication package
  • spring.jpa.hibernate.ddl-auto: none, validate, update, create, create-drop (default for embedded databases)

Exam traps

  • A method name that doesn't match an entity property makes startup fail (PropertyReferenceException)
  • @Modifying is mandatory on an UPDATE/DELETE @Query, and it needs a transaction
  • nativeQuery queries use table and column names; JPQL ones, entity and property names
  • Outside @SpringBootApplication (another root package) you need @EnableJpaRepositories and @EntityScan
  • Page runs an extra count query; if you don't need the total, use Slice or List

← Spring Data JPA · Run it