The 30 second answer
JPA is the standard Java API for mapping objects to tables, and Hibernate is the usual implementation. Spring Data JPA removes the boilerplate: I declare an interface that extends JpaRepository, and Spring creates the implementation at runtime with save, findById, findAll, delete and paging. It can also derive queries from method names like findByEmail, and for anything complex I write @Query. I still have to watch the generated SQL, especially for N+1 queries.
<!-- level: 1 --> <!-- must_know: true -->
@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
private String email;
private String status;
}
public interface CustomerRepository extends JpaRepository<Customer, Long> {
Optional<Customer> findByEmail(String email); // derived query
List<Customer> findByStatusOrderByEmailAsc(String status); // derived query
@Query("select c from Customer c where c.email like %:domain")
List<Customer> findByEmailDomain(String domain);
}- JPA (Jakarta Persistence) is the specification:
@Entity,@Id, relationships, theEntityManagerand JPQL. Hibernate is the implementation Spring Boot uses by default. - Spring Data JPA creates a proxy that implements your interface.
JpaRepositorygives CRUD, paging and sorting methods without any code. - Derived queries: Spring Data parses method names such as
findByEmailorfindByStatusOrderByEmailAscand builds the query.@Queryis for queries that names can't express. - What to say next: turn on SQL logging in development, watch for the N+1 problem with lazy relationships, and return DTOs from controllers instead of entities. Those follow-ups are in Fetch one hundred orders, call getItems on each?.
Sources (2)
- Spring Data JPA: Core concepts (repositories)docs.spring.io
- Spring Data JPA: Defining query methodsdocs.spring.io