Spring Boot findById() and orElseThrow() Example: Return 404 When a Record Is Missing


 

Spring Boot findById() and orElseThrow() Example: Return 404 When a Record Is Missing

Build a Spring Data JPA endpoint that returns a Kanban task when it exists and responds with 404 Not Found when the ID doesn’t match a row.

Spring Boot findById() and orElseThrow() Example

Suppose your Kanban board opens a task by calling GET /api/tasks/42. If task 42 exists, the API should return its details. If someone deleted it while the board was open, the API should return 404 Not Found.

Spring Data JPA gives you the first part of this solution. findById(id) returns an Optional containing the entity or an empty Optional when no record matches. Use orElseThrow() to decide what the missing record means for your API.

The quick answer

For a Spring MVC endpoint, pass a ResponseStatusException with HttpStatus.NOT_FOUND to orElseThrow().

Task task = taskRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(
HttpStatus.NOT_FOUND,
"Task " + id + " was not found"
));

When the task exists, orElseThrow() returns it. When the result is empty, the lambda creates the exception and Spring MVC uses its HTTP status. Calling orElseThrow() with no arguments instead would throw NoSuchElementException, which Spring MVC does not automatically treat as a 404.

1. Set up the Spring Boot project

Create a Maven project using Spring Initializr with Spring Boot 3.x, Java 17 or later, and these dependencies.

Dependency Purpose Spring Web Exposes the REST endpoints through Spring MVC Spring Data JPA Provides JpaRepository and its findById() method H2 Database Lets you run the example locally without installing a database server

Use com.example.kanban as the package for the examples below. Keep the generated @SpringBootApplication class in that package so Spring can discover the entity, repository, and controller. Spring Data generates the repository implementation from the interface.

2. Create the Task entity

This version uses a Long primary key. The client supplies a numeric ID in the URL, and the repository uses the same type for its lookup.

package com.example.kanban;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
protected Task() {
}
public Task(String title) {
this.title = title;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
}

The protected no-argument constructor is for JPA. The public constructor lets application code create a task by supplying its title.

3. Create the Spring Data JPA repository

package com.example.kanban;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TaskRepository extends JpaRepository<Task, Long> {
}

JpaRepository<Task, Long> gives this repository access to findById(Long id). Its return type is Optional<Task>. An ID with no matching row produces Optional.empty(). A null argument is invalid and throws IllegalArgumentException.

That gives us two separate decisions. The repository tells us whether a row exists. The HTTP endpoint decides whether that result should become a 404 response.

4. Build the REST endpoint

Add a POST endpoint so you can create a task and use its actual database-generated ID to test the GET endpoint.

package com.example.kanban;

import java.net.URI;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
private final TaskRepository taskRepository;
public TaskController(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
@PostMapping
public ResponseEntity<TaskResponse> createTask(
@RequestBody CreateTaskRequest request)
{
if (request.title() == null || request.title().isBlank()) {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST,
"A task title is required"
);
}
Task savedTask = taskRepository.save(new Task(request.title()));
URI location = URI.create("/api/tasks/" + savedTask.getId());
return ResponseEntity.created(location)
.body(TaskResponse.from(savedTask));
}
@GetMapping("/{id}")
public TaskResponse getTask(@PathVariable("id") Long id) {
Task task = taskRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(
HttpStatus.NOT_FOUND,
"Task " + id + " was not found"
));
return TaskResponse.from(task);
}
public record CreateTaskRequest(String title) {
}
public record TaskResponse(Long id, String title) {
static TaskResponse from(Task task) {
return new TaskResponse(task.getId(), task.getTitle());
}
}
}

The client receives a TaskResponse with the two fields the API exposes. Inside getTask(), the response is created only after the repository lookup succeeds. If there’s no matching task, the exception ends the method before TaskResponse.from(task) runs.

What does () -> new ResponseStatusException(...) do?

The lambda supplies an exception. orElseThrow() calls it only when the Optional is empty. If the task exists, Java returns the task without creating that exception. This overload is also why you can choose an exception that describes the operation, such as “Task 42 was not found.” docs.oracle.com

5. Test a successful lookup and a missing record

Start the application from the project root.

./mvnw spring-boot:run

On Windows PowerShell, use .\mvnw.cmd spring-boot:run.

Create a task

curl -i -X POST http://localhost:8080/api/tasks \
-H 'Content-Type: application/json
' \
-d '
{"title":"Review pull request"}'

The endpoint should return 201 Created, a Location header, and a JSON body similar to this.

{
"id": 1,
"title": "Review pull request"
}

Fetch the task using the returned ID

Replace 1 with the ID from your response.

curl -i http://localhost:8080/api/tasks/1

Expected result: 200 OK with the task’s ID and title.

Try an ID that doesn’t exist

curl -i http://localhost:8080/api/tasks/999999

Expected result: 404 Not Found if that ID is absent. Check the HTTP status first. Spring’s error response format and configuration determine whether the body also includes the reason string. docs.spring.io

Try an ID that can’t be parsed

curl -i http://localhost:8080/api/tasks/abc

Expected result: 400 Bad Request with Spring MVC’s default exception handling. The endpoint expects a Long, so Spring rejects abc during argument conversion before calling getTask(). docs.spring.io

Request Expected status What happened GET /api/tasks/1 200 OK The ID matches an existing task GET /api/tasks/999999 404 Not Found The ID is valid, but the task is absent GET /api/tasks/abc 400 Bad Request The ID cannot be converted to a Long

When should you use a custom exception?

A ResponseStatusException is straightforward when the lookup lives in an HTTP controller. If you move task lookup into a service that also runs in a scheduled job or another non-HTTP caller, the service can throw TaskNotFoundException and let the web layer decide how to represent it over HTTP.

The lookup then reads like this inside the service.

public Task findTask(Long id) {
return taskRepository.findById(id)
.orElseThrow(() -> new TaskNotFoundException(id));
}

Add the exception and handler within the application package.

public class TaskNotFoundException extends RuntimeException {
public TaskNotFoundException(Long id) {
super("Task " + id + " was not found");
}
}
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(TaskNotFoundException.class)
public ProblemDetail handleTaskNotFound(TaskNotFoundException exception) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.NOT_FOUND,
exception.getMessage()
);
problem.setTitle("Task not found");
return problem;
}
}

Returning ProblemDetail lets you define the status, title, and detail that clients receive. This is handy when the frontend needs a consistent error body across several endpoints.

orElseThrow() vs ResponseEntity.of()

If your endpoint only needs to return a body when the record exists and an empty 404 when it doesn’t, ResponseEntity.of() can handle the Optional directly.

@GetMapping("/{id}")
public ResponseEntity<TaskResponse> getTask(@PathVariable("id") Long id) {
return ResponseEntity.of(
taskRepository.findById(id).map(TaskResponse::from)
);
}

Use this version as a replacement for the earlier GET method. Choose orElseThrow() when you need a named exception, a specific error message, or a shared handler that builds your API’s error response.

Common questions

Why does findById(id).get() throw NoSuchElementException?

Optional.get() throws NoSuchElementException when the result is empty. You get the same default exception from a no-argument call to orElseThrow(). If the missing row should produce a 404, pass a ResponseStatusException or use a custom exception with an HTTP handler.

Should I call existsById() before findById()?

If you need the task itself, call findById() once and handle its result. Checking existsById() first can add another database operation, and a task could be deleted between the existence check and the lookup. Use existsById() when the only information you need is whether the record exists.

Why am I getting 404 for a task I can see in the database?

Check the ID your frontend sends and the datasource your API is connected to. findById() uses the entity’s primary key. If your frontend sends a task code such as KAN-42 but your primary key is a numeric id, look up the code through a repository method such as findByCode(String code). Also check whether your app is running against the local H2 database while you’re inspecting a separate database.

Does this work with MongoDB?

Yes. If your Kanban project uses Spring Data MongoDB with string IDs, use MongoRepository<Task, String> and receive the path variable as a String. The findById(id).orElseThrow(...) pattern stays the same. The entity mapping and how you validate the ID depend on your MongoDB model.

Does a database failure also become a 404?

A 404 here means the lookup completed and returned an empty Optional. If the database is unavailable and the repository call throws, execution never reaches orElseThrow(). That distinction matters because the frontend should treat a deleted task differently from a temporary service failure.

The pattern to remember

Use findById() when you need a record by its primary key. Use orElseThrow() when an empty lookup should stop the current operation. In a REST resource lookup, supply a 404 exception when the requested record is missing.

For a plain Java example of both overloads, see my earlier story, orElseThrow() in Java.

Post a Comment

0 Comments