Java Spring CrudRepository .orElseThrow()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26727812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:10:37  来源:igfitidea点击:

Spring CrudRepository .orElseThrow()

javaspringjava-8crudspring-boot

提问by szxnyc

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 :

如果数据库查询返回空,抛出异常的正确方法是什么?我正在尝试使用该.orElseThrow()方法,但它无法编译:

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)

“可选类型中的方法 orElseThrow(Supplier) 不适用于参数 (MeetingRestController.MeetingDoesNotExistException)

Is it possible to do this with lambda expressions?

可以用 lambda 表达式做到这一点吗?

CrudRepository :

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.");
  }
}

采纳答案by Eran

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

尝试传递类型为 的 lambda 表达式Supplier<MeetingDoesNotExistException>

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

回答by Jason C

The error means what it says.

错误意味着它所说的。

The documentation for orElseThrowstates that it takes a Supplieras a parameter.

的文档orElseThrow说明它将 aSupplier作为参数。

You have stated your exception is a RuntimeException, which is not a Supplier. Therefore, orElseThrow()is not applicable to that argument type. You would have to pass it a Supplier, not a RuntimeException.

您已经声明您的异常是 a RuntimeException,而不是 a Supplier。因此,orElseThrow()不适用于该参数类型。您必须将其传递给 a Supplier,而不是 a RuntimeException

It would be simpler syntax to use a lambda expression.

使用 lambda 表达式会更简单的语法。