0

I am new to Spring Boot. I am following this tutorial:

https://spring.io/guides/tutorials/rest/

In this tutorial, there is an interface declaration like this:

package payroll;

import org.springframework.data.jpa.repository.JpaRepository;

interface EmployeeRepository extends JpaRepository<Employee, Long> {

}

First question; Why do we declare this interface? In the code followed during tutorial, if I put JpaRepository<Employee, Long> instead of EmployeeRepository, everything works as before. Why would I use EmployeRepository interface, while original interface is there?

Second question; how is the interface is implemented and created an object of this implementation automatically by Spring Boot? What is the magic behind?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Murat
  • 35
  • 7
  • 1. Because you can add new methods to `EmployeeRepository`. 2. See e.g. https://stackoverflow.com/q/56032969/3001761. – jonrsharpe Oct 04 '21 at 19:43

1 Answers1

2
  1. In your EmployeeRepository you could add more methods in addition to the ones already available in JpaRepository. You can achieve this simply by adding the methods and Spring will parse their names creating the corresponding query. You can learn more about this at https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods. Additionally, EmployeeRepository is easier to read and understand than JpaRepository<Employee, Long>. this will actually help you and others read your code.

  2. You can read more about this also in https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods, but the very specific and dirty details can only be found in Spring Framework code itself.

João Dias
  • 16,277
  • 6
  • 33
  • 45
  • 1
    Also, later you could choose some other framework to implement your Employee repository without having to re-write everything that touched it – Gus Oct 05 '21 at 14:47