java - Spring Boot - 抛出异常或指示未找到项目

标签 java spring spring-boot

我编写了两个方法,findById 在数据库中搜索项目,如果找不到该项目,则抛出异常:

public Url findById(final Long id){
        return urlRepository.findById(id)
                .orElseThrow(() -> new ShortUrlNotFoundException("URL not found for the given ID"));
}

第二种方法,findByShortUrl 在数据库中搜索项目并使用 JPA 方法 findByShortUrlIs,如果满足以下条件,则返回大小为 1 的列表:找到该项目,对于给定的shortUrl,数据库中的项目永远不应该超过1个:

public Optional<String> findByShortUrl(final String shortUrl){

    List<Url> urlList = urlRepository.findByShortUrlIs(shortUrl);
    if(urlList.isEmpty()){
        return Optional.empty();
    }
    else {
        return Optional.of(urlList.get(0).getLongUrl());
    }
}

我喜欢在未找到项目时使用 ShortUrlNotFoundException 的模式。我应该在 findByShortUrl 中使用它吗?然后,findByShortUrl 变为:

public Optional<String> findByShortUrl(final String shortUrl){

    List<Url> urlList = urlRepository.findByShortUrlIs(shortUrl);
    if(urlList.isEmpty()){
        throw new ShortUrlNotFoundException("URL not found for the given ID")
    }
    else {
        return Optional.of(urlList.get(0).getLongUrl());
    }
}

最佳答案

为什么不使用 findFirst 如下:

Optional<Url> findFirstByShortUrlIs(String shortUrl);

然后,您调用:

public Optional<String> findByShortUrl(final String shortUrl){
        return urlRepository.findFirstByShortUrlIs(shortUrl)
                .map(Url::getLongUrl)
                .map(Optional::of)
                .orElseThrow(() -> new ShortUrlNotFoundException("URL not found for the given ID"));
}

关于java - Spring Boot - 抛出异常或指示未找到项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63700961/

相关文章:

java - 我无法理解 kotlin 中 string.kt 的源代码实现

java - Scala -> Java,将函数作为参数传递给另一个函数

java - Spring/Eclipse 项目突然记录一切

java - RestTemplate.postForObject返回ResponseEntity和Http错误时返回Null

java - jboss 服务器中的 Spring Boot War 未加载静态内容

Java EE 应用程序无法解析 Cookie 符号

java - 带有包含 URL 的字符串参数的 RequestMapping

java - 创建类路径资源中定义的名称为 'processEngine' 的 bean 时出错

java - Spring Boot 测试无法使用 LocalServerPort 注释 Autowiring 端口

java - 复制二进制文件会将换行符更改为窗口标准..? java