Junior — Middle
What are the main differences between the CrudRepository and JpaRepository interfaces in Spring Data?
sobes.tech AI
Answer from AI
CrudRepository and JpaRepository are interfaces from Spring Data that provide methods for working with a database, but they have some differences:
-
CrudRepository is a basic interface that offers core CRUD operations (Create, Read, Update, Delete). Methods include
save(),findById(),findAll(),deleteById(), etc. -
JpaRepository extends
PagingAndSortingRepository, which in turn extendsCrudRepository. It adds additional methods for JPA-specific operations, such as:- Methods for pagination and sorting (
findAll(Pageable pageable),findAll(Sort sort)) - Methods for batch saving (
saveAll()) - Methods for batch deletion
- Methods for pagination and sorting (
Thus, JpaRepository provides a richer set of functionalities focused on JPA, including convenient methods for pagination and sorting, whereas CrudRepository contains only basic CRUD operations.
Example:
public interface UserRepository extends JpaRepository<User, Long> {
// You can use methods from JpaRepository and CrudRepository
}