Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

Spring Boot JpaRepository with Example

JpaRepository is an interface provided by Spring Data JPA. When you extend this interface, you get a lot of CRUD (Create, Read, Update, Delete) operations for your entity without writing any implementation code. Additionally, JpaRepository provides methods for pagination and sorting out-of-the-box.

Let's walk through an example to demonstrate how to use JpaRepository in a Spring Boot application:

  1. Setting Up the Project:

    Create a Spring Boot project and add the following dependencies in your pom.xml:

    <!-- Spring Boot Starter Data JPA -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    
    <!-- Database driver (e.g., H2 for demonstration purposes) -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    
  2. Entity Creation:

    Create an Employee entity with JPA annotations:

    @Entity
    public class Employee {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String name;
        private String department;
    
        // Constructors, getters, setters, etc.
    }
    
  3. Create Repository Interface:

    Define an interface for Employee that extends JpaRepository:

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

    Note: The findByDepartment method is a custom query method, and Spring Data JPA will automatically generate a query based on the method name.

  4. Service Layer:

    Create a service class that uses the EmployeeRepository:

    @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> getEmployeesByDepartment(String department) {
            return employeeRepository.findByDepartment(department);
        }
    
        public Employee saveEmployee(Employee employee) {
            return employeeRepository.save(employee);
        }
    
        public void deleteEmployee(Long id) {
            employeeRepository.deleteById(id);
        }
    }
    
  5. Controller Layer:

    Now, you can create a RESTful controller to expose the operations:

    @RestController
    @RequestMapping("/employees")
    public class EmployeeController {
        @Autowired
        private EmployeeService employeeService;
    
        @GetMapping
        public List<Employee> getAllEmployees() {
            return employeeService.getAllEmployees();
        }
    
        @GetMapping("/{id}")
        public Employee getEmployeeById(@PathVariable Long id) {
            return employeeService.getEmployeeById(id);
        }
    
        @PostMapping
        public Employee createEmployee(@RequestBody Employee employee) {
            return employeeService.saveEmployee(employee);
        }
    
        // Other endpoints for update, delete, etc.
    }
    
  6. Running the Application:

    Start your Spring Boot application. If you've set up the necessary database configurations, your application will be able to perform CRUD operations on the Employee entity using the provided endpoints.

With Spring Boot and JpaRepository, a lot of the repetitive code related to data access is abstracted away, allowing developers to focus on the business logic.

  1. Using JpaRepository in Spring Boot example:

    • Utilize JpaRepository in a Spring Boot application to simplify data access.
    @Entity
    public class User {
        // Entity details...
    }
    
    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {
        // CRUD operations provided by JpaRepository
    }
    
  2. Spring Boot JpaRepository CRUD operations:

    • JpaRepository provides CRUD operations out of the box. Extend it in your repository interface.
    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {
        // CRUD operations are inherited
    }
    
  3. JpaRepository custom queries in Spring Boot:

    • Add custom queries in the repository interface. Spring Data JPA automatically generates queries based on the method names.
    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {
    
        List<User> findByUsername(String username);
    
        @Query("SELECT u FROM User u WHERE u.email = :email")
        List<User> findByEmail(@Param("email") String email);
    }
    
  4. Spring Boot JpaRepository pagination example:

    • Implement pagination in Spring Boot using JpaRepository.
    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {
    
        Page<User> findAll(Pageable pageable);
    }
    
  5. How to create a repository in Spring Boot:

    • Create a repository in Spring Boot by defining an interface that extends JpaRepository.
    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {
        // Custom queries or methods can be added here
    }
    
  6. Spring Boot JpaRepository save method example:

    • Use the save method of JpaRepository to persist entities.
    @Service
    public class UserService {
    
        @Autowired
        private UserRepository userRepository;
    
        public void saveUser(User user) {
            userRepository.save(user);
        }
    }
    
  7. Query methods in JpaRepository Spring Boot:

    • Define query methods in the repository interface. Spring Data JPA generates the corresponding queries.
    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {
    
        List<User> findByUsernameAndEmail(String username, String email);
    
        List<User> findByEmailLike(String email);
    }
    
  8. Spring Boot JpaRepository findBy example:

    • Use the findBy prefix to create query methods in JpaRepository.
    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {
    
        List<User> findByUsername(String username);
    
        List<User> findByEmailLike(String email);
    }
    
  9. Implementing JpaRepository in Spring Boot:

    • Implement JpaRepository in a Spring Boot application by defining a repository interface.
    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {
        // Custom queries or methods can be added here
    }