Video in progress

Junior 🌱 Spring

How does a repository interface work in Spring Data JPA, given that we never write its implementation?

At startup Spring builds a proxy for the interface. Standard methods like save and findById come from the ready-made SimpleJpaRepository; the rest are turned into queries from the method name or from @Query.

📖 Answer

public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findByCategoryAndPriceLessThan(String category, BigDecimal max);
}

You only write the interface. At startup Spring Data:

  1. finds interfaces that extend JpaRepository;
  2. builds a dynamic proxy for each one and registers it as a bean;
  3. forwards save, findById, findAll, deleteById calls to SimpleJpaRepository;
  4. parses methods like findByCategoryAndPriceLessThan by name and builds a JPQL query.

If the method name is wrong (for example, a field the entity doesn't have), the application fails at startup — it's good that the error shows up early.

A repository is an ordinary bean; you inject it into a service through the constructor. By default its methods run inside a transaction: reads are readOnly, save/delete run in a write transaction.