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:
- Create Java Interface that extends one of:
Repository,CrudRepository,PagingAndSortingRepository,JpaRepository
- Create class with
@Entityannotation
- Inside
@Entityclass, create a simple primary key annotated with@Idannotation or create class that will represent complex key annotated with@EmbeddedIdannotation at field level and@Embeddableat key class definition level
- Use
@EnableJpaRepositoriesto 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.