Bird
Raised Fist0
Spring Bootframework~10 mins

Service calling repository in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

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
Concept Flow - Service calling repository
Client calls Service method
Service method starts
Service calls Repository method
Repository accesses Database
Repository returns data to Service
Service processes data
Service returns result to Client
This flow shows how a client calls a service method, which then calls the repository to get data from the database, processes it, and returns the result.
Execution Sample
Spring Boot
public class UserService {
  private final UserRepository repo;
  public UserService(UserRepository repo) { this.repo = repo; }
  public User getUserById(Long id) {
    return repo.findById(id).orElse(null);
  }
}
A service method calls the repository to find a user by ID and returns the user or null.
Execution Table
StepActionService StateRepository CallRepository ResultService Return
1Client calls getUserById(5)WaitingNo call yetNo resultNo return
2Service calls repo.findById(5)Calling repofindById(5)Searching DBNo return
3Repository queries DB for ID=5Waiting repoDB queryUser{id=5}No return
4Repository returns User to ServiceReceived UserCompletedUser{id=5}No return
5Service returns User to ClientDoneNo callNo resultUser{id=5}
6Client receives UserIdleNo callNo resultUser{id=5}
💡 Execution stops after service returns the user to the client.
Variable Tracker
VariableStartAfter Step 2After Step 4Final
idnull555
repo.findById resultnullPendingUser{id=5}User{id=5}
service returnnullnullUser{id=5}User{id=5}
Key Moments - 2 Insights
Why does the service call the repository instead of accessing the database directly?
The service calls the repository to separate concerns: the repository handles data access, while the service handles business logic. This is shown in steps 2 and 3 where the service calls repo.findById and the repository queries the database.
What happens if the repository does not find a user with the given ID?
If the repository returns empty, the service returns null as shown by orElse(null) in the code. This would be reflected in the execution table by repo.findById result being empty and service return being null.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the repository result at step 3?
AUser{id=5}
BSearching DB
CNo result
DDB query
💡 Hint
Check the 'Repository Result' column at step 3 in the execution_table.
At which step does the service receive the user from the repository?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Service State' and 'Repository Result' columns to find when the service has the user.
If the repository returned empty, what would the service return?
AUser object
Bnull
CException
DEmpty list
💡 Hint
Refer to the code line with orElse(null) in the execution_sample.
Concept Snapshot
Service calls repository to get data.
Repository handles database access.
Service processes and returns data.
Use dependency injection for repository in service.
Service method calls repo method and returns result.
Keep responsibilities separate for clean code.
Full Transcript
In Spring Boot, a service class calls a repository class to get data from the database. The client calls a method on the service. The service method calls the repository method, which queries the database. The repository returns data to the service. The service processes or directly returns this data to the client. This separation keeps code organized and easier to maintain. The example shows a service method getUserById calling repo.findById and returning the user or null if not found.

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

  1. Step 1: Understand the role of Service

    The Service layer contains business logic and does not directly access the database.
  2. Step 2: Understand the role of Repository

    The Repository handles data access and database operations.
  3. Final Answer:

    To handle business logic and use the repository for data access -> Option D
  4. 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

  1. Step 1: Understand dependency injection in Spring Boot

    Spring Boot recommends constructor injection with @Autowired for better testability and immutability.
  2. Step 2: Check options for repository injection

    Creating new instances manually or static variables break Spring's management and are not recommended.
  3. Final Answer:

    Use @Autowired on a constructor parameter -> Option A
  4. 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

  1. Step 1: Understand repository method behavior

    findById(id) returns an Optional containing the User if found.
  2. Step 2: Analyze service method logic

    The method maps the User to its name or returns "Unknown" if no user is found.
  3. Final Answer:

    "Alice" -> Option C
  4. 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

  1. Step 1: Check repository injection

    The repository field is declared but not injected or initialized.
  2. Step 2: Understand consequence of missing injection

    Calling save on a null repository causes NullPointerException at runtime.
  3. Final Answer:

    The repository is not injected, so it will cause a NullPointerException -> Option B
  4. 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

  1. Step 1: Identify repository method for active users

    The repository method findByActiveTrue() returns users with active = true.
  2. Step 2: Use repository method in service

    The service should call this method and return its result directly.
  3. Final Answer:

    public List<User> getActiveUsers() { return userRepository.findByActiveTrue(); } -> Option A
  4. Quick Check:

    Call matching repository method for active users [OK]
Hint: Call repository method matching your filter [OK]
Common Mistakes:
  • Calling findAll() returns all users, not filtered
  • Using findByActiveFalse() returns inactive users
  • Returning null instead of data