当通过jap通过id查询时,使用 findById(id).get(),当id不存在当,也就是数据库没有对应当id数据时,就回报上面当异常
后来查看源码,发现:
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
也就是说当查不到值的时候,jap统一处理为抛异常,所以每次取之前都要判断有没有数据,后来发现了这个
public boolean isPresent() {
return value != null;
}
于是代码就这样写
Optional<T> optionalT = orderDetailRepository.findById(id);
return optionalT.isPresent() ? optionalT.get(): null;
网友评论