inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발

JPA를 이용한 새 게시물 추가 - HTTP POST Method

500 Internal Server Error

1688

oᅳob다영

작성한 질문수 1

0

안녕하세요 선생님, 수업 잘 듣고있습니다.

POST 방식으로 http://localhost:8088/jpa/users/9001/posts를  Request했을 때 500 Internal Server Error가 나오는데, 어떻게 해결해야할 지 모르겠습니다ㅠㅠ

[Postman]

[UserJpaController.java]


@PostMapping ("/users/{id}/posts")
public ResponseEntity<Post> createPost(@PathVariable int id, @RequestBody Post post){
Optional<User> user = userRepository.findById(id);

if (!user.isPresent()) {
throw new UserNotFoundException(String.format("ID{%s} not found",id));
}

//Post의 User를 방금 조회한 User정보로 설정


post.setUser(user.get());
// logger.info(String.valueOf(user.get()));
Post savedPost = postRepository.save(post);

//id 값을 자동으로 지정
URI location =ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedPost.getId())
.toUri();

return ResponseEntity.created(location).build();
}

[Debugging시 에러 메세지]

UserJpaController.java 파일에서 post.setUser(user.get());에서 발생

[Post.java]

public class Post {
@Id
@GeneratedValue
private Integer id;

private String description;

@ManyToOne(fetch = FetchType.LAZY)
@JsonIgnore
private User user;
}

[User.java]

@OneToMany(mappedBy = "user")
private List<Post> posts;

public User(int id, String name, Date joinDate, String password, String ssn) {
this.id = id;
this.name = name;
this.joinDate = joinDate;
this.password = password;
this.ssn = ssn;
}

spring-boot rest-api

답변 1

0

Dowon Lee

안녕하세요, 이도원입니다.

올려주는 오류는 디버그 시 나왔던 메시지하고는 다른 원인인것 같습니다. 

디버그 시 보여지는 "Method threw 'java.lang.StackOverflowError" 오류는 Optional 데이터를 사용했기 때문에 보여지는 오류인데, 실제 에러라기 보다는 디버깅 모드에서만 보여지는 현상입니다. 물론 Optional 객체에서 데이터가 존재하지 않는 null 상태일 수도 있겠지만, 그건 바로 위 코드인 isPresent() 메소드에서 확인하고 있기 때문에, user.get()을 사용하는 부분에서는 null 데이터는 아닙니다. 

IntelliJ에서 디보깅 시 위와 같은 메시지를 보지 않으시려면, 디버깅 창에서 해당 부분을 선택하시고, 마우스 우측버튼을 클릭하신다음, View as > Object로 선택하시면, 됩니다. 

위에 말씀드린 것 처럼, 디버그 모드에 보여주는 에러 메시지 외에 다른 오류가 있을 것 같습니다. 콘솔화면에 출력된 메시지를 다시 한번 공유해 주시면, 오류 원인을 찾아보도록 하겠습니다. 

감사합니다. 

JPA

0

57

1

jpa dependency를 추가하고 SecurityConfig클래스에서 오류가 납니다.

0

68

1

웹 브라우저 400 bad request

0

70

1

@Size는 되는데 @Past는 안 됩니다.

0

61

1

pdf 자료는 없나요?

0

73

2

locale 정보가 null 이면 무조건 messages_ko.properties이 호출 되는 문제

0

87

2

Swagger 강의, Unable to infer base url 이거 뜨시는 분들 도움되시라고

0

118

1

강의에서나온 화면 피피티

0

158

1

HelloWorldBean 관련 에러

0

182

2

Swagger API 3.x 오류..

0

218

1

java: variable message not initialized in the default constructor 에러는 어찌하면 좋을까요?

1

282

1

현재 GIT에 올리신 소스를 실행해봤습니다.

0

188

2

고양이 소리가 귀엽네요 !!

0

137

2

git에서 소스받고 실습중인데

0

117

1

post가 안되요

0

102

1

한국어 같은 경우 언어코드인 messages_ko.properties 로 생성하는게 더 좋지 않나요?

0

167

2

리턴타입으로서 EntityModel<User> 와 ResponseEntity질문

0

103

1

예외처리쪽 관련 질문있습니다.

0

159

2

엔티티가 바로 응답으로 나가도 되나요??

0

220

2

안녕하세여 Cannot invoke "co.kr.joneconsulting.resfulservice.repository.PostRepository.save(Object)" because "this.postRepository" is null

0

135

2

사용자 등록하고 나서 H2 에서 보면 신규 사용자의 password, ssn 이 null 로 되어 있습니다.

0

140

2

ApplictionContext 질문

0

190

2

롬북이 안먹히는것같아요

0

156

1

인텔리제이에서스프링부트 파일 실행하면

0

239

1