Concept Explanation
In the JDBC module you wrote every query by hand. Spring Data JPA removes most of that: you declare an interface, and Spring generates the implementation at runtime from the method names.
The Entity
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
private BigDecimal price; // BigDecimal for money, never double
protected Product() { } // JPA requires a no-arg constructor
public Product(String name, BigDecimal price) {
this.name = name;
this.price = price;
}
// getters omitted
}
The Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
// Derived queries — Spring writes the SQL from the method name
List<Product> findByName(String name);
List<Product> findByPriceLessThan(BigDecimal max);
List<Product> findByNameContainingIgnoreCase(String fragment);
Optional<Product> findFirstByOrderByPriceDesc();
// When derivation is not enough, write it explicitly
@Query("SELECT p FROM Product p WHERE p.price BETWEEN :low AND :high")
List<Product> inRange(@Param("low") BigDecimal low,
@Param("high") BigDecimal high);
}
You write no implementation class. Extending JpaRepository already gives you save, findById, findAll, deleteById, count, and paging.
Using It
@Service
public class ProductService {
private final ProductRepository repo;
public ProductService(ProductRepository repo) {
this.repo = repo;
}
@Transactional
public Product create(String name, BigDecimal price) {
return repo.save(new Product(name, price));
}
public Page<Product> page(int number) {
return repo.findAll(PageRequest.of(number, 20, Sort.by("name")));
}
}
The N+1 Problem
The classic JPA performance trap. Loading 100 orders and touching order.getCustomer() on each fires 1 query for the orders plus 100 more for customers.
Fix it with a fetch join:
@Query("SELECT o FROM Order o JOIN FETCH o.customer")
List<Order> findAllWithCustomer();
Common Mistakes
doublefor money: Rounding errors compound. AlwaysBigDecimal.FetchType.EAGEReverywhere: Loads half the database on every query. Default toLAZY.- Ignoring N+1: Everything is fast with 10 test rows and collapses with 10,000.
- Missing no-arg constructor: JPA instantiates entities reflectively and will fail without one.
Best Practices
- Return
Optionalfrom single-result finders, so absence is explicit. - Page every list endpoint:
findAll()on a large table will exhaust memory. - Enable
spring.jpa.show-sql=truein development to see exactly what Hibernate runs. - Never use
ddl-auto=updatein production — use a migration tool such as Flyway.
Practice Exercises
- The Derived Query: Add three derived finders to a repository and verify the generated SQL with
show-sqlenabled. - The N+1 Hunt: Build a lazy one-to-many, loop over the parents touching the children, count the queries in the log, then fix it with
JOIN FETCH. - The Paged Endpoint: Return page 2 of products sorted by price descending, 20 per page.