Skip to content
Advertisement

In which cases does JpaRepository automatically create the query without you having to use @Query annotation

I am following a Udemy tutorial in Spring boot. There’s a part where @Query wasn’t used for a user-created method in the repository interface. It works, but I want to understand when JpaRepository takes care of the creation of query. In the User class below, @Table wasn’t used.

findByEmail(String email) method works without any implementation/definition. So, my impression was that, JpaRepository automatically created the Select from User where email = emailargument

So here’s what I have

A database named reservation with table User

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/reservation
spring.datasource.username=root

User.java

import javax.persistence.Entity;

@Entity
public class User extends AbstractEntity{

    
    private String firstName;
    private String lastName;
    private String email;
    private String password;
    
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

UserRepository.java

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

import com.project.flightreservation.entities.User;

public interface UserRepository extends JpaRepository<User, Long> {

User findByEmail(String email);

}

Advertisement

Answer

When Spring Data creates a new Repository implementation, it analyses all the methods defined by the interfaces and tries to automatically generate queries from the method names. While this has some limitations, it’s a very powerful and elegant way of defining new custom access methods with very little effort. Ref

by implementing one of the Repository interfaces, the DAO will already have some basic CRUD methods (and queries) defined and implemented.

You can create more complex queries with this approach reference The one which you posted in question is called automatic custom query.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement