如果數據庫查詢返回空值,那麼拋出異常的正確方法是什麼?我試圖用.orElseThrow()
方法,但它不會編譯:Spring CrudRepository .orElseThrow()
Meeting meeting = meetingRepository.findByMeetingId(meetingId).orElseThrow(new MeetingDoesNotExistException(meetingId));
編譯器說:
「他法orElseThrow(供應商)在類型可選不適用於參數(MeetingRestController.MeetingDoesNotExistException)
是否有可能與lambda表達式做到這一點?
鉻udRepository:
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
public interface MeetingRepository extends CrudRepository<Meeting, Long>{
Optional<Meeting> findByMeetingId(Long id);
}
例外:
@ResponseStatus(HttpStatus.CONFLICT) // 409
class MeetingDoesNotExistException extends RuntimeException{
public MeetingDoesNotExistException(long meetingId){
super("Meeting " + meetingId + " does not exist.");
}
}
工作!謝謝! – szxnyc 2014-11-04 04:36:39