【问题标题】:Not being able to get a single object by using primary key in method FindById()无法通过在方法 FindById() 中使用主键来获取单个对象
【发布时间】:2019-06-16 07:15:29
【问题描述】:

我有一个表 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);
    }

这里。 我究竟做错了什么?如果你能帮忙就太好了。

【问题讨论】:

    标签: java spring-boot spring-data-jpa


    【解决方案1】:

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

    Optional&lt;T&gt; findById(ID id)

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

    【讨论】:

    • 如果您使用 Spring boot 2.x,@SubhaBhowmik findOne() 不接受 ID。您应该使用findById(..) 并使用Optional 做一些事情。一个可能(但不好)的解决方案是使用repository.findById(..).orElse(null)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    相关资源
    最近更新 更多