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.
- In the box
- Every box query was a hand-written EntityManager method. Declare an interface, let Spring Data implement it, write queries just by naming methods, and understand what Spring Boot does underneath and what the persistence context is.
AthleteService calls findByDivision() on JpaAthleteDao, highlighted in red, which sends createQuery() to the EntityManager connected to the database.
The Athlete entity, highlighted in amber, next to the EntityManager, which creates the athlete table in the database.
The AthleteRepository proxy and SimpleJpaRepository, highlighted: the proxy passes it save() and count().
AthleteService sends findByName("Ana") to the proxy, highlighted, and SimpleJpaRepository translates the name into JPQL for the EntityManager.
The proxy and the EntityManager, highlighted: the @Query query reaches the EntityManager exactly as written.
AthleteService sends PageRequest.of(0, 1) to the AthleteRepository proxy, highlighted.
AthleteService, the EntityManager and the entity, highlighted: setName() changes the managed entity and the UPDATE goes to the database on commit.
The context, the repository proxy and the EntityManager, highlighted: pieces Spring Boot auto-configures.
Final view: controller, service and repository proxy on top; SimpleJpaRepository, the entity and the EntityManager below, connected to the database.
Step 1 of 9
One method per query
JpaAthleteDao uses JPA's EntityManager to talk to the database: find to look up by id, createQuery with JPQL to filter, persist to save…
It works, but every entity needs its own DAO with the same methods (find, count, delete, page…) written again, and each new query is another method with its JPQL, its parameters and its getResultList().
Step 2 of 9
The entity: one class, one table
JPA maps classes to tables with annotations:
@Entity: the class is a persistent entity (tableathlete).@Id+@GeneratedValue: the primary key, generated by the database (IDENTITY).@Column: column details (nullable,unique,length).@OneToMany(mappedBy = "athlete")/@ManyToOne: relationships. The@ManyToOneside (WodResult.athlete) holds the foreign key.- A no-arg constructor (it can be
protected): JPA needs it to create instances.
Step 3 of 9
An interface and Spring Data does the rest
AthleteRepository is just an interface extending JpaRepository<Athlete, Long> (entity type and id type). You don't implement it.
At startup, Spring Data creates a proxy of that interface. Inherited calls (save, findById, findAll, count, deleteById, existsById…) are handled by SimpleJpaRepository, which uses the EntityManager for you.
The hierarchy:
Repository: a marker, no methods.CrudRepository/ListCrudRepository: CRUD (IterableorList).PagingAndSortingRepository:findAll(Pageable)andfindAll(Sort).JpaRepository: all of the above plusflush,saveAndFlush, batch deletes…
Step 4 of 9
Queries derived from the name
Declare a method whose name follows the rules and Spring Data generates the query:
findByName(String)→where a.name = ?findByDivisionOrderByNameAsc(String)→where a.division = ? order by a.name asccountByDivision,existsByNameIgnoreCase,deleteBy…findByNameContainingIgnoreCase→ case-insensitivelike %…%findTop3ByWodOrderBySecondsAsc→ the 3 best times
Other keywords: And, Or, Between, LessThan, GreaterThanEqual, IsNull, In, StartingWith, Not, First/Top…
Step 5 of 9
@Query: when the name isn't enough
For more complex queries, @Query:
- JPQL (the default): written with entities and properties, not tables:
select a from Athlete a where size(a.results) >= :min. - Native SQL:
nativeQuery = true, with table and column names. - Parameters by name (
:min+@Param("min")) or by position (?1). @ModifyingforUPDATE/DELETE; it returns the affected rows and needs a transaction.
Step 6 of 9
Paging and sorting
Add a Pageable parameter and return a Page<T>:
PageRequest.of(0, 1, Sort.by("name").descending()): page 0 (pages start at 0), size 1, by name descending.Pagebrings the content and the totals (getTotalElements(),getTotalPages()), for which Spring Data runs an extracountquery.- If you don't need the total, return
Slice<T>orList<T>. findAll(Sort.by("name"))sorts without paging.
Step 7 of 9
The persistence context
AthleteService.rename() is @Transactional: it reads the athlete, changes the name… and doesn't call save. Still, the change is stored. Why?
Inside a transaction, the EntityManager keeps a persistence context: the entities it loads become managed. Before the commit it flushes: it compares each managed entity with its original state and issues the needed UPDATEs. That's dirty checking.
The test checks it with TestEntityManager: flush() to send the changes and clear() to forget the cache and really read from the database.
Step 8 of 9
What Spring Boot does for you
With spring-boot-starter-data-jpa and a driver on the classpath, Spring Boot:
- Creates the
DataSource(here an in-memory H2). - Creates the
EntityManagerFactorywith Hibernate and theJpaTransactionManager. - Scans entities and repositories from the package of the
@SpringBootApplicationclass (equivalent to@EntityScanand@EnableJpaRepositories). - Applies properties like
spring.jpa.hibernate.ddl-auto,spring.jpa.show-sqlorspring.jpa.open-in-view.
For tests, @DataJpaTest starts only that layer, with an embedded database and a rollback at the end of each test. The first test also checks that the repository is a proxy and its target class is SimpleJpaRepository.
Step 9 of 9
Recap
@Entitymaps classes to tables; JPA needs@Idand a no-arg constructor.JpaRepository<T, ID>: an interface, and Spring generates the proxy (SimpleJpaRepository).- Derived queries by name, validated at startup;
@Queryfor JPQL or native SQL;@Modifyingfor writes. Pageable/Page/Sortto page and sort.- Dirty checking: managed entities save themselves on commit.
- Boot auto-configures everything;
@DataJpaTesttests the layer.
Code
JpaAthleteDao.java
/** Before: one hand-written method per query, all of them alike. */
public class JpaAthleteDao {
private final EntityManager em;
public JpaAthleteDao(EntityManager em) {
this.em = em;
}
public Optional<Athlete> findById(long id) {
return Optional.ofNullable(em.find(Athlete.class, id));
}
public List<Athlete> findByDivision(String division) {
return em.createQuery("select a from Athlete a where a.division = :d order by a.name", Athlete.class)
.setParameter("d", division)
.getResultList();
}
public Athlete save(Athlete athlete) {
em.persist(athlete);
return athlete;
}
// … count, delete, exists, paging, sorting: by hand, for every entity
}Athlete.java
@Entity // a JPA entity: one row of table "athlete"
public class Athlete {
@Id // primary key
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, length = 80)
private String name;
@Column(nullable = false, length = 10)
private String division;
@OneToMany(mappedBy = "athlete") // the other side owns the foreign key
private List<WodResult> results = new ArrayList<>();
protected Athlete() { // JPA needs a no-arg constructor
}
// …
}AthleteRepository.java
public interface AthleteRepository extends JpaRepository<Athlete, Long> { // entity type, id type
// save, findById, findAll, count, deleteById, existsById… come for free
// …
}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%AthleteRepository.java
@Query("select a from Athlete a where size(a.results) >= :min") // JPQL: entities and fields
List<Athlete> regulars(@Param("min") int min);
@Query(value = "SELECT * FROM athlete WHERE division = ?1", nativeQuery = true) // plain SQL
List<Athlete> nativeByDivision(String division);
@Modifying // an UPDATE/DELETE, not a select
@Query("update Athlete a set a.division = :to where a.division = :from")
int moveAll(@Param("from") String from, @Param("to") String to);AthleteRepositoryTest.java
@Test
void pagingAndSorting() {
Page<Athlete> page = athletes.findByDivision("RX",
PageRequest.of(0, 1, Sort.by("name").descending())); // page 0, size 1, name desc
assertThat(page.getContent()).extracting(Athlete::getName).containsExactly("Leo");
assertThat(page.getTotalElements()).isEqualTo(2); // an extra count query
assertThat(page.getTotalPages()).isEqualTo(2);
assertThat(athletes.findAll(Sort.by("name"))).first().extracting(Athlete::getName).isEqualTo("Ana");
}AthleteService.java
@Transactional
public void rename(long id, String newName) {
Athlete athlete = athletes.findById(id).orElseThrow(); // managed by the persistence context
athlete.setName(newName); // no save(): the change is flushed at commit
}AthleteRepositoryTest.java
@Test
void theRepositoryIsAGeneratedProxy() {
assertThat(Proxy.isProxyClass(athletes.getClass())).isTrue(); // a JDK proxy of the interface
assertThat(AopUtils.getTargetClass(athletes)).isEqualTo(SimpleJpaRepository.class); // does the work
assertThat(athletes.count()).isEqualTo(4); // inherited CRUD
Athlete saved = athletes.save(new Athlete("Zoe", "RX"));
assertThat(saved.getId()).isNotNull();
}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%