Spring Data JPA: Repositories for Free

Spring Data JPA: Repositories for Free in Java: In the JDBC module you wrote every query by hand.

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

  1. double for money: Rounding errors compound. Always BigDecimal.
  2. FetchType.EAGER everywhere: Loads half the database on every query. Default to LAZY.
  3. Ignoring N+1: Everything is fast with 10 test rows and collapses with 10,000.
  4. Missing no-arg constructor: JPA instantiates entities reflectively and will fail without one.

Best Practices

  • Return Optional from single-result finders, so absence is explicit.
  • Page every list endpoint: findAll() on a large table will exhaust memory.
  • Enable spring.jpa.show-sql=true in development to see exactly what Hibernate runs.
  • Never use ddl-auto=update in production — use a migration tool such as Flyway.

Practice Exercises

  1. The Derived Query: Add three derived finders to a repository and verify the generated SQL with show-sql enabled.
  2. 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.
  3. The Paged Endpoint: Return page 2 of products sorted by price descending, 20 per page.