JPA Repository

JpaRepository is an interface in Spring Data that provides a set of common CRUD (Create, Read, Update, Delete) operations for working with JPA entities. It extends the PagingAndSortingRepository interface and provides additional methods for querying data.

Here's an example of using JpaRepository in a Spring Boot application:

1. Define a JPA entity, for example:

            
    @Entity
    @Table(name = "employees")
    public class Employee {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "employee_id")
        private Long id;

        @Column(name = "first_name")
        private String firstName;

        @Column(name = "last_name")
        private String lastName;

        @Column(name = "email")
        private String email;

        // constructors, getters, and setters
    }
            
        

2. Create a JpaRepository for the Employee entity, for example:

            
    @Repository
    public interface EmployeeRepository extends JpaRepository<Employee, Long> {
        List<Employee> findByLastName(String lastName);
    }
            
        

In this example, we've created a EmployeeRepository interface that extends the JpaRepository interface for the Employee entity. We've also defined a custom query method to find employees by last name.

3. Use the repository to persist and retrieve data, for 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 List<Employee> getEmployeesByLastName(String lastName) {
            return employeeRepository.findByLastName(lastName);
        }

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

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

In this example, we've created a EmployeeService class that uses the EmployeeRepository to perform CRUD operations on the Employee entity. We've also defined additional methods to find employees by last name and delete employees by ID.

That's an example of using JpaRepository in a Spring Boot application to work with JPA entities