public UserInfo findUserInfoByIdAndName(int age, String name) throws Exception { if (StringUtils.isBlank(name)) { throw new Exception("名称不能为空"); } if (age < 0 || age > 120) { throw new Exception("年龄超出范围"); } UserInfoExample example = new UserInfoExample(); UserInfoExample.Criteria criteria = example.createCriteria(); criteria.andNameEqualTo(name); criteria.andAgeBetween(age - 10, age + 10); List<UserInfo> list = userInfoMapper.selectByExample(example); if (list == null || list.size() == 0) { throw new Exception("未找到符合条件的用户"); } return list.get(0); }优化代码
时间: 2024-01-27 08:04:49 浏览: 71
以下是对业务层代码的优化:
```java
@Service
public class DeviceService {
@Autowired
private UserInfoMapper userInfoMapper;
public UserInfo findUserInfoByIdAndName(int age, String name) throws Exception {
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("名称不能为空");
}
if (age < 0 || age > 120) {
throw new IllegalArgumentException("年龄超出范围");
}
UserInfoExample example = new UserInfoExample();
UserInfoExample.Criteria criteria = example.createCriteria();
criteria.andNameEqualTo(name);
criteria.andAgeBetween(age - 10, age + 10);
List<UserInfo> list = userInfoMapper.selectByExample(example);
if (CollectionUtils.isEmpty(list)) {
throw new NotFoundException("未找到符合条件的用户");
}
return list.get(0);
}
}
```
这里使用了IllegalArgumentException和NotFoundException来替代Exception,使得代码更加规范。同时使用了CollectionUtils.isEmpty方法来判断list是否为空,代码更加简洁。
阅读全文