Video in progress
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:
- finds interfaces that extend
JpaRepository; - builds a dynamic proxy for each one and registers it as a bean;
- forwards
save,findById,findAll,deleteByIdcalls toSimpleJpaRepository; - parses methods like
findByCategoryAndPriceLessThanby 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.
Sign up to mark studied questions and save your progress.