Java 17: NullPointerException when using Optional in Spring Data JPA repository queries
I'm sure I'm missing something obvious here, but I'm working with a `NullPointerException` in my Spring Data JPA repository when trying to use `Optional` to handle potential null values. I have an entity `User` and I'm attempting to retrieve a user by email. Here's the relevant code snippet: ```java @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(unique = true) private String email; // Getters and Setters } public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByEmail(String email); } ``` In my service class, I'm calling the repository method like this: ```java @Autowired private UserRepository userRepository; public User getUserByEmail(String email) { return userRepository.findByEmail(email) .orElseThrow(() -> new EntityNotFoundException("User not found")); } ``` However, when I pass a non-existent email, instead of throwing the `EntityNotFoundException`, I get a `NullPointerException`: ``` java.lang.NullPointerException at com.example.service.UserService.getUserByEmail(UserService.java:15) ``` I've checked to ensure the email is indeed not in the database, and I suspect the scenario could be related to how the `Optional` is being handled. I've tried debugging but need to pinpoint the cause. Does anyone know how to resolve this scenario or if there's a best practice for using `Optional` in Spring Data JPA repositories that I might be missing? I'd really appreciate any guidance on this. For reference, this is a production desktop app. Thanks for taking the time to read this!