Repaso
Español
Spring, JPA & Java WebIntermediateSPR-16

What does a Spring Data JPA repository interface give you?

public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);
}

Options

  1. Nothing until you write the SQL for every single method
  2. Ready-made CRUD methods and queries from method names (Correct option)
  3. Only read operations, with no way of saving any data
  4. A web page to browse the data stored in the database

Answer

Ready-made CRUD methods (save, findById, findAll, deleteById) plus queries generated from method names such as findByEmail

Why

You only declare an interface. At startup Spring Data creates the implementation for you.

JpaRepository<User, Long> gives CRUD methods, paging and sorting. Method names like findByEmail or findByAgeGreaterThanAndActiveTrue are parsed and turned into queries automatically (derived queries).

For complicated queries, use @Query("select ...") with JPQL or native SQL.

Remember

Declare the interface; Spring writes the implementation.

Key terms

Practice this question in Repaso