The JpaRepository interface helps you easily manage database operations without writing SQL. It saves time by providing ready-made methods for common tasks like saving, finding, and deleting data.
JpaRepository interface in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
public interface YourEntityRepository extends JpaRepository<YourEntity, Long> {
// custom query methods if needed
}YourEntity is the class representing your database table.
Long is the type of the primary key (ID) of your entity.
User entities with an Integer ID. It also adds a method to find users by their last name.public interface UserRepository extends JpaRepository<User, Integer> {
List<User> findByLastName(String lastName);
}Product entities with Long IDs, using only built-in methods.public interface ProductRepository extends JpaRepository<Product, Long> {
// No extra methods needed for basic CRUD
}This example defines a Book entity and a BookRepository that extends JpaRepository. It shows saving books and finding books by author using the repository methods.
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import jakarta.persistence.*; import java.util.List; import org.springframework.stereotype.Service; @Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String author; // Constructors, getters, setters public Book() {} public Book(String title, String author) { this.title = title; this.author = author; } public Long getId() { return id; } public String getTitle() { return title; } public String getAuthor() { return author; } public void setTitle(String title) { this.title = title; } public void setAuthor(String author) { this.author = author; } } @Repository public interface BookRepository extends JpaRepository<Book, Long> { List<Book> findByAuthor(String author); } // Usage in a service or controller @Service public class BookService { private final BookRepository bookRepository; public BookService(BookRepository bookRepository) { this.bookRepository = bookRepository; } public void demo() { Book book1 = new Book("Spring Boot Guide", "Alice"); Book book2 = new Book("Java Basics", "Bob"); bookRepository.save(book1); bookRepository.save(book2); List<Book> booksByAlice = bookRepository.findByAuthor("Alice"); booksByAlice.forEach(book -> System.out.println(book.getTitle())); } }
You don't need to implement JpaRepository methods yourself; Spring Data JPA does it automatically.
Use meaningful method names like findByAuthor to create custom queries without SQL.
Remember to annotate your repository interface with @Repository for Spring to detect it.
JpaRepository provides ready-to-use database methods for your entities.
It helps you avoid writing SQL and speeds up development.
Custom query methods can be added by following naming rules.
Practice
JpaRepository interface in Spring Boot?Solution
Step 1: Understand JpaRepository role
JpaRepository is designed to simplify database access by providing ready-made methods like save, findAll, and delete for entity classes.Step 2: Compare with other options
Options A, C, and D relate to REST API endpoints, security, and UI rendering, which are not responsibilities of JpaRepository.Final Answer:
To provide built-in methods for database operations on entities -> Option AQuick Check:
JpaRepository = database helper [OK]
- Confusing JpaRepository with REST controllers
- Thinking it manages security
- Assuming it handles UI rendering
User with primary key type Long using JpaRepository?Solution
Step 1: Check JpaRepository declaration syntax
JpaRepository is an interface that should be extended, not implemented. The generic parameters are , so is correct.Step 2: Validate each option
public interface UserRepository extends JpaRepository {} correctly extends JpaRepository with . public class UserRepository implements JpaRepository {} incorrectly uses implements and class. public interface UserRepository extends JpaRepository {} swaps generic types. public interface UserRepository extends Repository<User> {} uses Repository, not JpaRepository.Final Answer:
public interface UserRepository extends JpaRepository {} -> Option DQuick Check:
Extend JpaRepository [OK]
- Using implements instead of extends
- Swapping generic type order
- Using Repository instead of JpaRepository
List<User> findByLastName(String lastName);
What will this method do when called with
findByLastName("Smith")?Solution
Step 1: Understand method naming convention
JpaRepository supports query derivation by method names. 'findByLastName' means find all entities where lastName equals the given parameter.Step 2: Analyze return type and behavior
The return type is List<User>, so it returns all matching users with lastName exactly 'Smith'. It does not do partial matching or throw errors.Final Answer:
Return all User entities with lastName exactly 'Smith' -> Option AQuick Check:
findByProperty = exact match [OK]
- Assuming it does partial matching
- Expecting a single result instead of list
- Thinking method is invalid without @Query
public interface ProductRepository extends JpaRepository {
List<Product> findByPriceGreaterThan(Double price);
}Which of the following is a likely cause of a runtime error when calling
findByPriceGreaterThan(null)?Solution
Step 1: Check method name and support
JpaRepository supports keywords like GreaterThan for query derivation, so method name is valid and compiles fine.Step 2: Analyze passing null parameter
Passing null to a comparison query causes a NullPointerException at runtime because the query cannot compare with null.Final Answer:
Passing null causes a NullPointerException in the query generation -> Option CQuick Check:
Null param in comparison query = runtime error [OK]
- Thinking method name is invalid
- Assuming JpaRepository lacks GreaterThan support
- Believing return type causes error
OrderRepository that finds all orders placed between two dates. Which of the following method signatures correctly uses JpaRepository naming conventions to achieve this?Solution
Step 1: Recall JpaRepository method naming rules
JpaRepository supports keywords like Between to filter values between two parameters. The property name must match entity field, here 'OrderDate'.Step 2: Evaluate each method signature
List<Order> findByOrderDateBetween(LocalDate start, LocalDate end); uses 'findByOrderDateBetween' which is correct. Options B, C, and D use unsupported or incorrect keywords and will not work.Final Answer:
List<Order> findByOrderDateBetween(LocalDate start, LocalDate end); -> Option BQuick Check:
Use Between keyword for range queries [OK]
- Using unsupported keywords like 'Range' or 'BetweenDates'
- Not matching property name exactly
- Trying to create custom method without @Query but wrong name
