Performance: Service calling repository
This pattern affects backend response time and indirectly impacts frontend load speed and interaction responsiveness.
Jump into concepts and practice - no test required
public class UserService { @Autowired private UserRepository userRepository; public List<User> getAllUsers() { List<Long> ids = getUserIds(); return userRepository.findAllById(ids); } }
public class UserService { @Autowired private UserRepository userRepository; public List<User> getAllUsers() { List<User> users = new ArrayList<>(); for (Long id : getUserIds()) { users.add(userRepository.findById(id).orElse(null)); } return users; } }
| Pattern | Database Queries | Backend Latency | Network Payload | Verdict |
|---|---|---|---|---|
| Multiple repository calls in loop | N queries for N items | High due to query overhead | Normal | [X] Bad |
| Single batch repository call | 1 query for all items | Low due to reduced overhead | Normal | [OK] Good |
Service class in Spring Boot when it calls a Repository?@Autowired for better testability and immutability.@Autowired on a constructor parameter -> Option AgetUserName(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");
}
}findById(id) returns an Optional containing the User if found.@Service
public class ProductService {
private ProductRepository productRepository;
public void saveProduct(Product product) {
productRepository.save(product);
}
}save on a null repository causes NullPointerException at runtime.List<User> findByActiveTrue(). How should the service method call the repository and return the list?findByActiveTrue() returns users with active = true.