In this section, we will explore how to use Spring Data repositories to interact with the database in a Spring Boot application. Spring Data JPA provides a powerful and flexible way to manage data access layers, allowing developers to focus on the business logic rather than boilerplate code.

Key Concepts

  1. Spring Data JPA Repositories: Interfaces that provide CRUD operations and more complex queries.
  2. Repository Types: Different types of repositories like CrudRepository, JpaRepository, and PagingAndSortingRepository.
  3. Custom Queries: Methods to define custom queries using JPQL or native SQL.
  4. Query Methods: Methods to create queries based on method names.

Repository Types

CrudRepository

The CrudRepository interface provides CRUD functions:

public interface CrudRepository<T, ID> extends Repository<T, ID> {
    <S extends T> S save(S entity);
    Optional<T> findById(ID primaryKey);
    Iterable<T> findAll();
    long count();
    void delete(T entity);
    boolean existsById(ID primaryKey);
}

JpaRepository

The JpaRepository interface extends CrudRepository and provides additional JPA-specific methods:

public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID> {
    List<T> findAll();
    List<T> findAll(Sort sort);
    List<T> findAllById(Iterable<ID> ids);
    <S extends T> List<S> saveAll(Iterable<S> entities);
    void flush();
    <S extends T> S saveAndFlush(S entity);
    void deleteInBatch(Iterable<T> entities);
    void deleteAllInBatch();
}

PagingAndSortingRepository

The PagingAndSortingRepository interface provides methods for pagination and sorting:

public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {
    Iterable<T> findAll(Sort sort);
    Page<T> findAll(Pageable pageable);
}

Creating a Repository

To create a repository, you need to define an interface that extends one of the repository interfaces provided by Spring Data JPA.

Example

Let's assume we have an Employee entity:

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String department;
    private Double salary;

    // Getters and Setters
}

Now, we create a repository interface for the Employee entity:

public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    List<Employee> findByDepartment(String department);
    List<Employee> findBySalaryGreaterThan(Double salary);
}

Using the Repository

You can now use the EmployeeRepository in your service or controller to perform database operations.

Example

@Service
public class EmployeeService {
    @Autowired
    private EmployeeRepository employeeRepository;

    public List<Employee> getAllEmployees() {
        return employeeRepository.findAll();
    }

    public Employee getEmployeeById(Long id) {
        return employeeRepository.findById(id).orElse(null);
    }

    public Employee saveEmployee(Employee employee) {
        return employeeRepository.save(employee);
    }

    public void deleteEmployee(Long id) {
        employeeRepository.deleteById(id);
    }

    public List<Employee> getEmployeesByDepartment(String department) {
        return employeeRepository.findByDepartment(department);
    }

    public List<Employee> getEmployeesWithHighSalary(Double salary) {
        return employeeRepository.findBySalaryGreaterThan(salary);
    }
}

Practical Exercise

Task

  1. Create a new entity called Product with fields id, name, category, and price.
  2. Create a repository interface for the Product entity.
  3. Implement a service class to perform CRUD operations on Product.
  4. Add methods to find products by category and products with a price greater than a specified value.

Solution

Step 1: Create the Product Entity

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String category;
    private Double price;

    // Getters and Setters
}

Step 2: Create the ProductRepository Interface

public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findByCategory(String category);
    List<Product> findByPriceGreaterThan(Double price);
}

Step 3: Implement the ProductService Class

@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;

    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }

    public Product getProductById(Long id) {
        return productRepository.findById(id).orElse(null);
    }

    public Product saveProduct(Product product) {
        return productRepository.save(product);
    }

    public void deleteProduct(Long id) {
        productRepository.deleteById(id);
    }

    public List<Product> getProductsByCategory(String category) {
        return productRepository.findByCategory(category);
    }

    public List<Product> getProductsWithHighPrice(Double price) {
        return productRepository.findByPriceGreaterThan(price);
    }
}

Summary

In this section, we learned how to use Spring Data repositories to manage data access in a Spring Boot application. We covered the different types of repositories, how to create a repository interface, and how to use it in a service class. We also provided a practical exercise to reinforce the concepts learned. In the next section, we will delve into query methods in Spring Data JPA.

Spring Boot Course

Module 1: Introduction to Spring Boot

Module 2: Spring Boot Basics

Module 3: Building RESTful Web Services

Module 4: Data Access with Spring Boot

Module 5: Spring Boot Security

Module 6: Testing in Spring Boot

Module 7: Advanced Spring Boot Features

Module 8: Deploying Spring Boot Applications

Module 9: Performance and Monitoring

Module 10: Best Practices and Tips

© Copyright 2024. All rights reserved