Stop 14 · Spring Boot & Backend DevelopmentTopics · 7/13

Spring Data JPA

Part of the Java Roadmap

In short

You saw how much code JDBC needs. With Spring Data JPA, a one-line interface gives you save, find, delete, paging and sorting, and a method name like findByCity becomes a query.

Spring Data JPA generates repository implementations from interfaces. Extending JpaRepository gives you CRUD, paging and sorting, and method names like findByEmail become queries.

The jaadu as a librarian reads a small request slip and pulls exactly the right books from tall wooden shelves onto a trolley.

Think of it like this

The library request slip

At a college library you don't search the shelves yourself. You fill a slip that says "books by author R.K. Narayan, sorted by year" and the librarian brings them. Spring Data reads your method name the same way: findByAuthorOrderByYear is the slip, and Spring writes the query for you.

Watch it happen

How a method name becomes a query

find
0
By
1
City
2
And
3
Fees
4
LessThan
5
OrderBy
6
Name
7

1/5Spring Data splits the method name into parts at startup.

The big ideas

What you need to know

JpaRepository<T, ID>

Extend it and get save, findById, findAll, deleteById, count, paging and sorting for free.

Derived queries

findByEmail, existsByEmail, countByCity, findTop5ByOrderByCreatedAtDesc. Method names become JPQL.

@Query

For anything complex, write JPQL or native SQL on the method with named parameters.

Paging

Pass PageRequest.of(page, size, Sort.by("name")) and get a Page with content and total count.

See it in code

Walk through the code

java
1import org.springframework.data.domain.*;2import org.springframework.data.jpa.repository.*;3import org.springframework.data.repository.query.Param;4import java.util.*;5 6public interface StudentRepository extends JpaRepository<Student, Long> {7 8    Optional<Student> findByEmail(String email);9 10    boolean existsByEmail(String email);11 12    List<Student> findByCityAndFeesLessThanOrderByName(String city, int fees);13 14    Page<Student> findByCity(String city, Pageable pageable);15 16    @Query("SELECT s FROM Student s WHERE s.course.name = :course AND s.marks >= :min")17    List<Student> toppers(@Param("course") String course, @Param("min") int min);18}19 20// In a service21Page<Student> page = repo.findByCity("Pune", PageRequest.of(0, 20, Sort.by("name")));22System.out.println(page.getTotalElements() + " students, showing " + page.getNumberOfElements());

1/6Entity type and id type. This alone gives you full CRUD.

No implementation class anywhere. Spring creates one at startup and checks every method against the Student entity.

Save yourself the pain

Common mistakes

Oops

Calling findById(id).get() everywhere.

Do this instead

Use orElseThrow(() -> new StudentNotFoundException(id)) so a missing row gives a clear 404.

Oops

Writing a 60-character derived method name.

Do this instead

When a name gets hard to read, switch to @Query with a clear JPQL statement.

Oops

Loading findAll() and filtering in Java.

Do this instead

Filter in the query. Pulling 100,000 rows into memory to keep 10 is slow and wasteful.

Your mission

Repository playground

~30 min

Quick check

What happens if you declare findByCityy (typo) in a repository whose entity has a city field?

Go deeper

  1. 1Create a repository interface and use it from a service.
  2. 2Write derived query methods and one @Query method.
  3. 3Add pagination to a list endpoint with Pageable.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge