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)
classDiagram
direction LR
class Repository {
<<marker>>
}
class CrudRepository {
<<interface>>
+save(T) T
+findById(ID) Optional~T~
+count() long
+deleteById(ID)
}
class PagingAndSortingRepository {
<<interface>>
+findAll(Pageable) Page~T~
+findAll(Sort) Iterable~T~
}
class JpaRepository {
<<interface>>
+flush()
+saveAndFlush(T) T
}
class AthleteRepository {
<<your interface>>
+findByName(String) Optional~Athlete~
+findByDivisionOrderByNameAsc(String) List~Athlete~
+moveAll(from, to) int
}
class SimpleJpaRepository {
<<generated proxy target>>
}
Repository <|-- CrudRepository
CrudRepository <|-- PagingAndSortingRepository
PagingAndSortingRepository <|-- JpaRepository
JpaRepository <|-- AthleteRepository
JpaRepository <|.. SimpleJpaRepository
SimpleJpaRepository --> EntityManagerKey pieces
@Entity,@Id,@GeneratedValue,@Column,@OneToMany/@ManyToOneRepository→CrudRepository/ListCrudRepository→PagingAndSortingRepository→JpaRepository- Derived queries:
findBy…,countBy…,existsBy…,deleteBy…,findTop3By…OrderBy…,IgnoreCase,Containing,Between… @Query(JPQL ornativeQuery = true) +@Param;@Modifyingfor UPDATE/DELETEPageable,PageRequest.of(page, size, Sort),Page<T>,Sort@DataJpaTestandTestEntityManagerto 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 findByIdreturnsOptional<T>;saveinserts if new and merges otherwiseSimpleJpaRepository'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,EntityManagerFactoryandJpaTransactionManager, and scans entities and repositories from the@SpringBootApplicationpackage 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) @Modifyingis mandatory on an UPDATE/DELETE@Query, and it needs a transactionnativeQueryqueries use table and column names; JPQL ones, entity and property names- Outside
@SpringBootApplication(another root package) you need@EnableJpaRepositoriesand@EntityScan Pageruns an extracountquery; if you don't need the total, useSliceorList