我正在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"
}
UserRegistrationController
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);
}
答案 0 :(得分:1)
getOne
方法仅返回来自DB的引用(延迟加载)。因此,基本上您不在事务内(不考虑已在服务类中声明的Transactional),并且会发生错误。参见documentation
改为使用findOne
。