Discover how separating data access from business logic saves you hours of debugging and rewriting!
Why Service calling repository in Spring Boot? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine building a web app where you manually write code to fetch data from the database every time a user requests something. You mix database queries directly inside your business logic.
This approach quickly becomes messy and hard to maintain. If you want to change how data is fetched, you must hunt through all your code. It's easy to introduce bugs and hard to test parts separately.
Using a service calling a repository cleanly separates concerns. The repository handles data access, while the service focuses on business rules. This makes code easier to read, test, and update.
public class UserService {
public User getUser(int id) {
// direct DB query here
}
}public class UserService { private UserRepository repo; public User getUser(int id) { return repo.findById(id); } }
This pattern enables building clear, maintainable apps where data access and business logic evolve independently.
Think of an online store: the service calculates discounts and rules, while the repository fetches product info from the database.
Manual data access mixed with business logic is hard to maintain.
Service calling repository separates concerns clearly.
This leads to cleaner, testable, and flexible code.
Practice
Service class in Spring Boot when it calls a Repository?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 DQuick Check:
Service handles logic, Repository handles data [OK]
- Thinking Service manages database connections
- Confusing Repository with Service responsibilities
- Assuming Service runs SQL queries directly
Solution
Step 1: Understand dependency injection in Spring Boot
Spring Boot recommends constructor injection with@Autowiredfor 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@Autowiredon a constructor parameter -> Option AQuick Check:
Constructor injection with @Autowired [OK]
- Manually creating repository instances
- Using static variables for repository
- Not using Spring's dependency injection
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");
}
}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 CQuick Check:
User found returns name, else "Unknown" [OK]
- Assuming null is returned instead of default
- Expecting exception when user not found
- Confusing Optional usage
@Service
public class ProductService {
private ProductRepository productRepository;
public void saveProduct(Product product) {
productRepository.save(product);
}
}Solution
Step 1: Check repository injection
The repository field is declared but not injected or initialized.Step 2: Understand consequence of missing injection
Callingsaveon a null repository causes NullPointerException at runtime.Final Answer:
The repository is not injected, so it will cause a NullPointerException -> Option BQuick Check:
Missing injection causes null pointer error [OK]
- Forgetting @Autowired or constructor injection
- Assuming repository auto-initializes
- Confusing entity annotation with parameter
List<User> findByActiveTrue(). How should the service method call the repository and return the list?Solution
Step 1: Identify repository method for active users
The repository methodfindByActiveTrue()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 AQuick Check:
Call matching repository method for active users [OK]
- Calling findAll() returns all users, not filtered
- Using findByActiveFalse() returns inactive users
- Returning null instead of data
