CrudRepository is a Spring Data interface for basic persistence operations: creating, retrieving, updating, and deleting records. Extend it when an application needs those operations without declaring each one separately. section 14.2 section 14.5
A repository interface supplies two generic types: the model class and the type of its primary key. In Spring Data JDBC, mark the model’s primary key field with @Id so Spring Data can identify it. section 14.3
Listing 14.4 Defining the Spring Data repository
public interface AccountRepository
extends CrudRepository<Account, Long> {
}AccountRepository inherits CRUD operations for Account records, whose primary key type is Long. section 14.3
Spring Data provides a bean implementing the repository contract. Other components can inject it: for example, a transfer service can call findById to retrieve an account or findAll to retrieve all accounts. section 14.2 section 14.3
Choose a contract that fits the operations you need:
- Repository is a marker interface and declares no persistence operations. section 14.2
- CrudRepository adds basic CRUD operations. section 14.2
- PagingAndSortingRepository adds operations for sorting and retrieving records in pages. section 14.2
Inherited operations do not cover every query an application needs. A repository can declare a custom method such as findAccountsByName; Spring Data can derive its query from the method name. For more complex operations, use @Query to specify the query explicitly. Modifying operations also need @Modifying. section 14.3 section 14.5
Listing 14.5 Adding a repository operation to get all the accounts with a specified name
public interface AccountRepository
extends CrudRepository<Account, Long> {
List<Account> findAccountsByName(String name);
}This custom method adds a name-based search alongside the inherited CRUD operations. section 14.3


