我编写了两个方法,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/