enter image description here Why the code doesn't work and how can I fix it
or you can somehow rewrite this method in a different way, I'm struggling for the second day I didn't find anything worthwhile on the Internet
Controller
@PostMapping(value = "message/{id}",params = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Message createMessage(@RequestBody Message newMessage, @PathVariable("id") Long id){
return addMessage(newMessage,id);
}
private Message addMessage(Message message,Long id){
return messageRepository.save(new Message(message.getText(),userRepository.findById(id).get()));
}
Class
@Entity
@NoArgsConstructor
@Getter
@Setter
public class Message {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String text;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id")
private User author;
public Message(String text, User author) {
this.text = text;
this.author = author;
}
}
CodePudding user response:
I assume your RestController has RequestMapping set to "/api" - if dont then your url should be "localhost:8080/message/1".
If this does not help:
- make sure the request hit method "createMessage" (for example set breakpoint in debug mode in this method and then try call it from postman) - if dont then make sure your annotations were imported from "org.springframework.web.bind.annotation".
- make sure your body from postman is correct Message class
By the way:
- Consider using DTO or Request classes to pass entity in/out your REST application - it will help you avoid circular reference in future and problems with de/serialization your entity.
- Consider using ResponseEntity instead of returning object to output - method with ResponseEntity should be like: enter image description here