在springboot 2.0以上版本中,CrudRepository接口的findOne(T id)方法已经被官方移除。
以前findOne方法如果查询到没有结果就会返回null,2.0版本后出现getOne方法,但是查询到没有结果的时候就会报错,而不是返回null。
慎用getOne方法,选择findById方法代替。
findById方法返回的类型是Optional,进入Optional类中,有两个方法可以解决我们的问题。
/**
* If a value is present in this {@code Optional}, returns the value,
* otherwise throws {@code NoSuchElementException}.
*
* @return the non-null value held by this {@code Optional}
* @throws NoSuchElementException if there is no value present
*
* @see Optional#isPresent()
*/
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
调用这种方法前要进行isPresent()判断,这种方法在value值为null时会抛出异常。
@Override
public String getUserName(Long id) {
Optional<User> user = userDao.findById(id);
if (user.isPresent()) {
return user.get().getUserName();
} else {
return "查询无果";
}
/**
* Return the value if present, otherwise return {@code other}.
*
* @param other the value to be returned if there is no value present, may
* be null
* @return the value, if present, otherwise {@code other}
*/
public T orElse(T other) {
return value != null ? value : other;
}
这种方法在value值为null时可以自定义other值作为返回值。
@Override
public User getUser(Long id) {
return userDao.findById(id).orElse(null);
}