Card 01/ 06
Spring Data Repositories: CrudRepository and JpaRepository
Declare an interface with no method bodies, and Spring supplies save, findById, findAll and delete.
A repository in Spring Data is an interface you declare for one entity type (a class mapped to a database table), and Spring generates its implementation when the application starts. By extending one of Spring Data's base interfaces, the repository gets the everyday database operations without a line of SQL.
interface RideRepository extends JpaRepository<RideEntity, Long> {} has no methods of its own, yet any bean it is injected into can call save, findById, findAll and delete on it. The two type arguments are the entity class and the type of its id, here RideEntity and Long.
CrudRepository is the base: create, read, update and delete, and nothing else. JpaRepository combines those operations (through ListCrudRepository, which returns lists instead of iterables) with paging and sorting (through ListPagingAndSortingRepository), and adds methods specific to JPA, such as flush() and saveAllAndFlush(), which push pending changes to the database immediately.
Extend CrudRepository when basic reading and writing is genuinely all a repository needs, or when you want the repository to say nothing about JPA. Extend JpaRepository, the more common choice in a JPA application, when you need paging, sorting or explicit flushing.
So a repository interface is a contract you write and Spring fulfils: choose the base interface by the operations you need, and add only the queries that the base does not already provide.
← → move through sections and cards