java基础----Optional,简化代码
1.判断获取的对象是否为空,空则抛出异常
原代码
UserInfoPo userInfoPo = userInfoMapper.queryUserInfo(userId);
if (null == userInfoPo ) {
throw new PlatformException(ErrorCode.USER_NOT_EXIST);
}
简化后的代码
UserInfoPo userInfoPo = Optional.of(termInfoMapper.queryUserInfo(userId))
.orElseThrow(() -> new PlatformException(ErrorCode.USER_NOT_EXIST));
2.判断获取的对象是否为空,不为空则抛出异常
原代码
if (null != userInfoMapper.queryByName(name)) {
throw new PlatformException(ErrorCode.USER_NAME_EXIST);
}
简化后的代码
if (userInfoMapper.queryByName(name).isPresent()) {
throw new PlatformException(ErrorCode.USER_NAME_EXIST);
}
mapper:
Optional<UserInfoPo> queryByName(@Param("name") String name);