Spring Data Repositories
Spring Data repositories, CrudRepository vs JpaRepository, custom queries, @EntityGraph, projections
1What is the main difference between JpaRepository and CrudRepository?
What is the main difference between JpaRepository and CrudRepository?
回答
JpaRepository extends both CrudRepository and PagingAndSortingRepository, adding JPA-specific methods like flush(), saveAndFlush(), and deleteInBatch(). CrudRepository only provides basic CRUD operations (save, findById, delete). Using JpaRepository gives access to all advanced JPA features without needing to compose multiple interfaces.
2What is the role of PagingAndSortingRepository in the repository hierarchy?
What is the role of PagingAndSortingRepository in the repository hierarchy?
回答
PagingAndSortingRepository extends CrudRepository by adding findAll(Pageable) and findAll(Sort) methods for pagination and sorting. This allows retrieving data in pages with Page/Slice and sorting results. JpaRepository extends this interface, thus providing pagination, sorting, and JPA-specific features in a single interface.
3What is the correct hierarchy of Spring Data repository interfaces?
What is the correct hierarchy of Spring Data repository interfaces?
回答
The correct hierarchy is Repository (base) → CrudRepository (CRUD) → PagingAndSortingRepository (pagination/sorting) → JpaRepository (JPA-specific). Each level adds features: CrudRepository adds save/delete, PagingAndSortingRepository adds pagination/sorting, and JpaRepository adds flush/batch. This architecture allows choosing the required feature level.
Which JpaRepository method allows immediately synchronizing changes with the database?
In which case prefer CrudRepository over JpaRepository?
+22 面接問題