JDBC, Transactions, Spring Data JPA
July 31, 2021

M03 Q26 How do you define a Repository interface? Why is it an interface not a class?

To define Repository interface, you need to follow those steps:

  1. Create Java Interface that extends one of: Repository, CrudRepository, PagingAndSortingRepository, JpaRepository
  1. Create class with @Entity annotation
  1. Inside @Entity class, create a simple primary key annotated with @Id annotation or create class that will represent complex key annotated with @EmbeddedId annotation at field level and @Embeddable at key class definition level
  1. Use @EnableJpaRepositories to point out package to scan for Repositories

Repository interface is an interface, not a class for Spring Data to be able to use JDK Dynamic Proxy to intercept all calls to repository and also to allow creation of custom base repositories for every DAO based on SimpleJpaRepository configured at @EnableJpaRepositories level.