How can I return Optional from @Query method?

Viewed 586

Is it possible to return optional from repository If @Query in Spring data JPA is used?

@Query("SELECT e FROM Employee m WHERE e.id=?1 AND e.card=?2")
Employee getById(Integer id, Card card); 
1 Answers

Yes, it is.

you just need to change the return type of your method to Optional<Employee>. Your method will look like:

   @Query("SELECT e FROM Employee m WHERE e.id=?1 AND e.card=?2")
   Optional<Employee> getById(Integer id, Card card); 
Related