# Understanding Repositories in Spring Data JPA!

Spring Data JPA provides several repository interfaces to facilitate data persistence and retrieval. These interfaces extend each other to build upon functionality, starting from basic CRUD operations to more advanced capabilities like pagination and sorting.

This article explores the following repository interfaces:

1. **CrudRepository**
    
2. **ListCrudRepository**
    
3. **JpaRepository**
    
4. **PagingAndSortingRepository**
    
5. **ListPagingAndSortingRepository**
    

---

## **Repository Hierarchy in Spring Data JPA**

### **Basic Structure**

```java
CrudRepository
   |
   --> PagingAndSortingRepository
         |
         --> JpaRepository
   |
   --> ListCrudRepository
         |
         --> ListPagingAndSortingRepository
```

### **Overview of Interfaces**

1. **CrudRepository**:
    
    * Provides CRUD operations: Create, Read, Update, Delete.
        
    * Returns `Optional` for nullable results.
        
2. **ListCrudRepository**:
    
    * An extension of `CrudRepository`.
        
    * Returns `List` instead of `Iterable` for find operations, making it easier to work with collections.
        
3. **PagingAndSortingRepository**:
    
    * Extends `CrudRepository`.
        
    * Adds support for pagination and sorting.
        
4. **JpaRepository**:
    
    * Extends `PagingAndSortingRepository`.
        
    * Provides JPA-specific methods like `flush()` and `saveAndFlush()`.
        
5. **ListPagingAndSortingRepository**:
    
    * Extends `ListCrudRepository`.
        
    * Combines `ListCrudRepository` and `PagingAndSortingRepository`.
        
    * Returns `List` instead of `Iterable` while supporting pagination and sorting.
        

---

## **CrudRepository**

### **Key Features**

* Basic CRUD operations.
    
* Methods:
    
    ```java
    Optional<T> findById(ID id);
    Iterable<T> findAll();
    void deleteById(ID id);
    T save(T entity);
    ```
    

### **Example**

```java
@Repository
public interface EmployeeCrudRepository extends CrudRepository<Employee, Long> {}

// Usage
@Autowired
private EmployeeCrudRepository repository;

public void demoCrud() {
    Employee emp = new Employee("John", "Developer");
    repository.save(emp); // Create
    
    Optional<Employee> retrievedEmp = repository.findById(emp.getId()); // Read
    repository.deleteById(emp.getId()); // Delete
}
```

---

## **ListCrudRepository**

### **Key Features**

* Returns `List` instead of `Iterable`, improving usability.
    

### **Example**

```java
@Repository
public interface EmployeeListCrudRepository extends ListCrudRepository<Employee, Long> {}

// Usage
@Autowired
private EmployeeListCrudRepository repository;

public void demoListCrud() {
    List<Employee> employees = repository.findAll(); // Returns a List instead of Iterable
}
```

---

## **PagingAndSortingRepository**

### **Key Features**

* Adds support for pagination and sorting.
    
* Methods:
    
    ```java
    Iterable<T> findAll(Sort sort);
    Page<T> findAll(Pageable pageable);
    ```
    

### **Example**

```java
@Repository
public interface EmployeePagingRepository extends PagingAndSortingRepository<Employee, Long> {}

// Usage
@Autowired
private EmployeePagingRepository repository;

public void demoPagingAndSorting() {
    Pageable pageable = PageRequest.of(0, 5, Sort.by("name").ascending());
    Page<Employee> page = repository.findAll(pageable);
}
```

---

## **JpaRepository**

### **Key Features**

* JPA-specific methods like `saveAndFlush`, `flush`, and `deleteInBatch`.
    
* Suitable for complex queries and JPA-specific use cases.
    

### **Example**

```java
@Repository
public interface EmployeeJpaRepository extends JpaRepository<Employee, Long> {}

// Usage
@Autowired
private EmployeeJpaRepository repository;

public void demoJpa() {
    repository.saveAndFlush(new Employee("Jane", "Manager")); // Saves and flushes immediately
    repository.deleteAllInBatch(); // Efficient batch delete
}
```

---

## **ListPagingAndSortingRepository**

### **Key Features**

* Combines `ListCrudRepository` with `PagingAndSortingRepository`.
    
* Supports pagination, sorting, and returns `List` instead of `Iterable`.
    

### **Example**

```java
@Repository
public interface EmployeeListPagingRepository extends ListPagingAndSortingRepository<Employee, Long> {}

// Usage
@Autowired
private EmployeeListPagingRepository repository;

public void demoListPagingAndSorting() {
    Pageable pageable = PageRequest.of(0, 5);
    List<Employee> employees = repository.findAll(pageable).getContent();
}
```

---

## **Comparison Table**

| **Repository Interface** | **CRUD Operations** | **Pagination/Sorting** | **JPA-Specific** | **Return Type for FindAll** |
| --- | --- | --- | --- | --- |
| CrudRepository | ✅ | ❌ | ❌ | `Iterable` |
| ListCrudRepository | ✅ | ❌ | ❌ | `List` |
| PagingAndSortingRepository | ✅ | ✅ | ❌ | `Iterable` |
| JpaRepository | ✅ | ✅ | ✅ | `List` |
| ListPagingAndSortingRepository | ✅ | ✅ | ❌ | `List` |

---

## **When to Use Each Repository**

* **CrudRepository**: For simple CRUD operations with minimal dependencies.
    
* **ListCrudRepository**: When working with collections and `List` is preferred.
    
* **PagingAndSortingRepository**: When pagination or sorting is required.
    
* **JpaRepository**: For advanced JPA-specific functionalities.
    
* **ListPagingAndSortingRepository**: When combining `ListCrudRepository` with pagination/sorting.
    

**More such articles:**

[**medium.com/techwasti**](https://medium.com/techwasti)

[**youtube.com/@maheshwarligade**](https://www.youtube.com/@maheshwarligade)

[**techwasti.com/series/spring-boot-tutorials**](https://techwasti.com/series/spring-boot-tutorials)

[**techwasti.com/series/go-language**](https://techwasti.com/series/go-language)
