Spring CrudRepository .orElseThrow()
2022-09-01 19:56:51
如果数据库查询返回空,引发异常的正确方法是什么?我正在尝试使用该方法,但它不会编译:.orElseThrow()
Meeting meeting = meetingRepository.findByMeetingId(meetingId).orElseThrow(new MeetingDoesNotExistException(meetingId));
编译器在说:
“he method orElseThrow(Supplier) 在 Type Optional 中不适用于参数 (MeetingRestController.MeetingDoesNotExistException)
是否可以使用 lambda 表达式执行此操作?
CrudRepository :
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.");
}
}