java - 无法通过在方法 FindById() 中使用主键来获取单个对象
问题描述
我有一个表 tbl_user,我试图在从路径变量中提供 id 时获取单个对象。但是,每当我尝试通过 findById() 创建方法时,它都会在服务部分出现错误。
桌子
CREATE TABLE `tbl_user` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) DEFAULT NULL,
`email` VARCHAR(255) NOT NULL,
`contact` VARCHAR(255) NOT NULL,
`status` ENUM('active','inactive') NOT NULL,
UNIQUE KEY `email` (`email`),
UNIQUE KEY `contact` (`contact`),
PRIMARY KEY (`id`)
);
控制器
@RequestMapping(value = "/find/user/{id}", method = RequestMethod.GET)
public JsonNode getUser(HttpServletRequest httpServletRequest, @PathVariable(value = "id") long userId) throws IOException {
JSONObject response = new JSONObject();
User user = new User();
try {
user = userService.getUserByUserId(userId);
if (user != null) {
response = utility.createResponseObject(200, KeyWord.SUCCESS, new JSONObject(utility.convertPOJOtoString(user)));
} else {
response = utility.createResponseObject(500, KeyWord.ERROR, new JSONObject());
}
} catch (Exception e) {
return objectMapper.readTree(utility.createResponse(500, KeyWord.ERROR, e.toString()).toString());
}
return objectMapper.readTree(response.toString());
}
服务
public User getUserByUserId(long userId) {
return userRepository.findById(userId);
}
存储库
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
我得到了红色下划线
public User getUserByUserId(long userId) {
return userRepository.findById(userId);
}
这里。我究竟做错了什么?如果您能提供帮助,那就太好了。
解决方案
如果您查看接口上的findById
定义,Repository
它会返回 Optional 而不是实体类:
Optional<T> findById(ID id)
返回:具有给定 id 的实体,如果没有找到,则返回 Optional#empty()
推荐阅读
- python - pandas 按列值减法
- python - 如何使用 python 在 adb shell 中读写
- c# - 当我尝试转换为 (int?) 时,指定的转换无效
- csv - 无法查看 Hive 外部表中的任何数据,该表存储为 HDFS 中包含印地语字符的 ORC
- node.js - Apollo v2 订阅 graphql
- r - R编程中不接受除空格外的特殊字符的正则表达式
- sql - 使用 Oracle SQL 删除重复数据并保留最新记录不起作用
- angular - 展开手风琴角材料时删除边距
- flutter - 将 SafeArea 添加到 SliverAppBar
- android - 如何将多个 EditText 值从 RecyclerView 适配器传递到主 Activity?