2014-11-04 85 views
6

如果數據庫查詢返回空值,那麼拋出異常的正確方法是什麼?我試圖用.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."); 
    } 
} 

回答

21

嘗試通過Supplier<MeetingDoesNotExistException>類型的lambda表達式:

Meeting meeting = 
    meetingRepository.findByMeetingId(meetingId) 
        .orElseThrow(() -> new MeetingDoesNotExistException(meetingId)); 
+0

工作!謝謝! – szxnyc 2014-11-04 04:36:39

0

錯誤說話是算數的。

orElseThrow的文檔聲明以Supplier作爲參數。

你已經聲明你的例外是RuntimeException,這不是Supplier。因此,orElseThrow()不適用於該參數類型。你將不得不通過它Supplier,而不是RuntimeException

使用lambda表達式會更簡單。

相關問題