Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring CrudRepository .orElseThrow()

Tags:

What is the proper way to throw an exception if a database query returns empty? I'm trying to use the .orElseThrow() method but it won't compile :

Meeting meeting = meetingRepository.findByMeetingId(meetingId).orElseThrow(new MeetingDoesNotExistException(meetingId)); 

The compiler is saying :

"he method orElseThrow(Supplier) in the type Optional is not applicable for the arguments (MeetingRestController.MeetingDoesNotExistException)

Is it possible to do this with lambda expressions?

CrudRepository :

import java.util.Optional;  import org.springframework.data.repository.CrudRepository;  public interface MeetingRepository extends CrudRepository<Meeting, Long>{     Optional<Meeting> findByMeetingId(Long id); } 

Exception :

@ResponseStatus(HttpStatus.CONFLICT) // 409 class MeetingDoesNotExistException extends RuntimeException{   public MeetingDoesNotExistException(long meetingId){     super("Meeting " + meetingId + " does not exist.");   } } 
like image 768
szxnyc Avatar asked Nov 04 '14 04:11

szxnyc


1 Answers

Try passing a lambda expression of type Supplier<MeetingDoesNotExistException> :

Meeting meeting =      meetingRepository.findByMeetingId(meetingId)                      .orElseThrow(() -> new MeetingDoesNotExistException(meetingId)); 
like image 115
Eran Avatar answered Sep 22 '22 19:09

Eran