gpt4 book ai didi

java - 如果我搜索数据库中不存在的用户 ID,则获取 org.springframework.http.converter.HttpMessageNotWritableException

转载 作者:行者123 更新时间:2023-12-02 10:26:34 25 4
gpt4 key购买 nike

我正在 Spring boot+JPA(MYSQL) 中构建 RESTAPI。如果我搜索数据库中不存在的用户 ID,我会收到以下错误响应:

{
"timestamp": 1545657449608,
"status": 500,
"error": "Internal Server Error",
"exception": "**org.springframework.http.converter.HttpMessageNotWritableException**",
"message": "Could not write content: Unable to find com.bookmyshow.user.User with id asd (through reference chain: com.bookmyshow.user.User_$$_jvst809_0[\"username\"]); nested exception is **com.fasterxml.jackson.databind.JsonMappingException**: Unable to find com.bookmyshow.user.User with id asd (through reference chain: com.bookmyshow.user.User_$$_jvst809_0[\"username\"])",
"path": "/users/asd"
}

用户注册 Controller

package com.bookmyshow.user;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserRegistrationController {

@Autowired
private UserDAO userDAO;

@RequestMapping("/users/{id}")
public ResponseEntity<?> getUser(@PathVariable String id) {

User user= userDAO.getUser(id);

if(user==null) {
return ResponseEntity.notFound().build();
}

return ResponseEntity.ok().body(user);
}

UserDAO

package com.bookmyshow.user;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserDAO {

@Autowired
UserRepository userRepository;

public User getUser(String id) {

System.out.println("USERDAO:"+id);
return userRepository.getOne(id);
}

最佳答案

getOne 方法仅返回来自数据库的引用(延迟加载)。所以基本上你在事务之外(不考虑你在服务类中声明的事务),并且发生错误。请参阅documentation

改用findOne

另请参阅when-use-getone-and-findone-methods-spring-data-jpa

关于java - 如果我搜索数据库中不存在的用户 ID,则获取 org.springframework.http.converter.HttpMessageNotWritableException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53914189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com