Category: java
Optional in Spring
Published on 01 May 2026
Explanation
What is Optional in Spring
Data JPA? π¦
Optional is used to handle
null values safely when retrieving data
from
the database. Instead of returning null,
methods
like findById() return Optional<T>,
helping avoid NullPointerException
and making code more readable.
Code:
Optional<User> user = userRepository. findById(id);
Explanation
Checking if Value Exists using
isPresent() β
Use isPresent() to check whether the
Optional object contains a value
before accessing
it. This prevents runtime errors.
Code:
Optional<User> user = userRepository.
findById(id);
if(user.isPresent()) {
System.out.println(user.get().getName());
}
Explanation
Using orElse() for Default Values
The orElse() method returns a default value
if the Optional object is empty, making
code safer and cleaner.
Code:
User user = userRepository.findById(id)
.orElse(new User());
Explanation
Using orElseThrow() for
Exception Handling
Use orElseThrow() when data must exist.
It
throws a custom exception if the value
is not found in the database.
Code:
User user = userRepository.findById(id)
.orElseThrow(() ->
new RuntimeException("User not found"));