首页 > 解决方案 > 无法通过在方法 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);
    }

这里。我究竟做错了什么?如果您能提供帮助,那就太好了。

标签: javaspring-bootspring-data-jpa

解决方案


如果您查看接口上的findById定义,Repository它会返回 Optional 而不是实体类:

Optional<T> findById(ID id)

返回:具有给定 id 的实体,如果没有找到,则返回 Optional#empty()


推荐阅读