Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Service Calling Repository in Spring Boot
📖 Scenario: You are building a simple Spring Boot application to manage books in a library. The application needs to store book information and retrieve it when requested.In this project, you will create a repository to hold book data and a service that calls this repository to get the list of books.
🎯 Goal: Build a Spring Boot service class that calls a repository class to fetch a list of books.This will help you understand how services and repositories work together in Spring Boot.
📋 What You'll Learn
Create a repository class with a method to return a list of book titles
Create a service class that calls the repository method
Use dependency injection to connect the service and repository
Return the list of books from the service method
💡 Why This Matters
🌍 Real World
In real applications, services call repositories to separate business logic from data access. This pattern helps keep code organized and easier to maintain.
💼 Career
Understanding how to connect services and repositories with Spring annotations is essential for backend development roles using Spring Boot.
Progress0 / 4 steps
1
Create the BookRepository class with a method to get books
Create a class called BookRepository with a method getBooks() that returns a List<String> containing exactly these book titles: "Spring Basics", "Java Fundamentals", "REST APIs".
Spring Boot
Hint
Use Arrays.asList to create the list of book titles inside the getBooks() method.
2
Add a service class with a repository field
Create a class called BookService with a private field bookRepository of type BookRepository. Add a constructor that takes a BookRepository parameter and assigns it to the bookRepository field.
Spring Boot
Hint
Use constructor injection to assign the bookRepository field.
3
Add a method in BookService to call the repository
In the BookService class, add a public method getAllBooks() that returns a List<String>. Inside this method, call bookRepository.getBooks() and return its result.
Spring Boot
Hint
Call the repository method inside the service method and return the list.
4
Add Spring annotations to connect service and repository
Add the @Repository annotation to the BookRepository class and the @Service annotation to the BookService class. Also, add the @Autowired annotation to the constructor of BookService to enable dependency injection.
Spring Boot
Hint
Use Spring annotations @Repository, @Service, and @Autowired to connect the classes.
Practice
(1/5)
1. What is the main role of a Service class in Spring Boot when it calls a Repository?
easy
A. To configure the database settings
B. To directly manage database connections
C. To replace the repository and perform SQL queries
D. To handle business logic and use the repository for data access
Solution
Step 1: Understand the role of Service
The Service layer contains business logic and does not directly access the database.
Step 2: Understand the role of Repository
The Repository handles data access and database operations.
Final Answer:
To handle business logic and use the repository for data access -> Option D
Quick Check:
Service handles logic, Repository handles data [OK]
Hint: Service = logic, Repository = data access [OK]
Common Mistakes:
Thinking Service manages database connections
Confusing Repository with Service responsibilities
Assuming Service runs SQL queries directly
2. Which is the correct way to inject a repository into a service class in Spring Boot?
easy
A. Use @Autowired on a constructor parameter
B. Create a new repository instance inside the service method
C. Use new keyword to instantiate repository in service constructor
D. Declare repository as a static variable in the service
Solution
Step 1: Understand dependency injection in Spring Boot
Spring Boot recommends constructor injection with @Autowired for better testability and immutability.
Step 2: Check options for repository injection
Creating new instances manually or static variables break Spring's management and are not recommended.
Final Answer:
Use @Autowired on a constructor parameter -> Option A
Quick Check:
Constructor injection with @Autowired [OK]
Hint: Use @Autowired constructor injection for repositories [OK]
Common Mistakes:
Manually creating repository instances
Using static variables for repository
Not using Spring's dependency injection
3. Given this service code snippet, what will getUserName(1) return if the repository finds a user with name "Alice"?
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public String getUserName(int id) {
return userRepository.findById(id).map(User::getName).orElse("Unknown");
}
}
medium
A. null
B. "Unknown"
C. "Alice"
D. Throws NullPointerException
Solution
Step 1: Understand repository method behavior
findById(id) returns an Optional containing the User if found.
Step 2: Analyze service method logic
The method maps the User to its name or returns "Unknown" if no user is found.
Final Answer:
"Alice" -> Option C
Quick Check:
User found returns name, else "Unknown" [OK]
Hint: Optional.map returns value or default [OK]
Common Mistakes:
Assuming null is returned instead of default
Expecting exception when user not found
Confusing Optional usage
4. What is wrong with this service code that calls a repository?
@Service
public class ProductService {
private ProductRepository productRepository;
public void saveProduct(Product product) {
productRepository.save(product);
}
}
medium
A. The save method does not exist in repositories
B. The repository is not injected, so it will cause a NullPointerException
C. The service class must be abstract
D. The Product parameter should be annotated with @Entity
Solution
Step 1: Check repository injection
The repository field is declared but not injected or initialized.
Step 2: Understand consequence of missing injection
Calling save on a null repository causes NullPointerException at runtime.
Final Answer:
The repository is not injected, so it will cause a NullPointerException -> Option B
Quick Check:
Missing injection causes null pointer error [OK]
Hint: Always inject repository before use [OK]
Common Mistakes:
Forgetting @Autowired or constructor injection
Assuming repository auto-initializes
Confusing entity annotation with parameter
5. You want to create a service method that returns all active users from the database. The repository has a method List<User> findByActiveTrue(). How should the service method call the repository and return the list?
hard
A. public List<User> getActiveUsers() { return userRepository.findByActiveTrue(); }
B. public List<User> getActiveUsers() { return userRepository.findAll(); }
C. public List<User> getActiveUsers() { return userRepository.findByActiveFalse(); }
D. public List<User> getActiveUsers() { return null; }
Solution
Step 1: Identify repository method for active users
The repository method findByActiveTrue() returns users with active = true.
Step 2: Use repository method in service
The service should call this method and return its result directly.
Final Answer:
public List<User> getActiveUsers() { return userRepository.findByActiveTrue(); } -> Option A
Quick Check:
Call matching repository method for active users [OK]
Hint: Call repository method matching your filter [OK]