Fak*_*ion 3 hibernate jpa spring-boot
I'm getting this exception when I try to save a topic with a message: nested exception is javax.persistence.EntityNotFoundException: Unable to find mypackage.model.Message with id fb8d39ea-0094-410d-975a-ea4495781422
Here is the model :
@Entity
public class Topic {
@Id
private String id;
private String title;
private String projectName;
private String author;
@OneToMany(mappedBy = "topicId")
private Set<Message> messages;
public Topic() {
this.messages = new HashSet<>();
}
}
@Entity
public class Message {
@Id
private String id;
private String author;
private String content;
private String topicId;
}
Run Code Online (Sandbox Code Playgroud)
The controller :
@RequestMapping(value = "/projects/{projectSubject}", method = RequestMethod.POST)
public String createTopic(Model model, @PathVariable("projectSubject") String subject,
@RequestParam("title") String title,
@RequestParam("message") String messageContent,
@RequestParam("author") String author,
@RequestParam("projectName") String projectName) {
Project project = projectService.findBySubject(projectName);
if(project != null){
Topic topic = new Topic();
topic.setId(UUID.randomUUID().toString());
topic.setAuthor(author);
topic.setProjectName(projectName);
topic.setTitle(title);
Message initialPost = new Message();
initialPost.setId(UUID.randomUUID().toString());
initialPost.setContent(messageContent);
initialPost.setAuthor(author);
topic.getMessages().add(initialPost);
topicService.saveTopic(topic);
}
return "topicList";
}
Run Code Online (Sandbox Code Playgroud)
The service :
public void saveTopic(Topic topic) {
topicRepository.save(topic);
}
Run Code Online (Sandbox Code Playgroud)
The repository :
public interface TopicRepository extends JpaRepository<Topic,String> {}
Run Code Online (Sandbox Code Playgroud)
Try this
@OneToMany(mappedBy = "topicId", cascade = {CascadeType.ALL})
private Set<Message> messages;
Run Code Online (Sandbox Code Playgroud)
when you don't specify cascadeType, then the framework thinks that messages inside the topic object you are about to save are already saved in the database and tries to search for those messages in Messages table so that it can associate that with the topic object it is about to save in Topic table.
If you specify cascade type then it saves all the child objects and then saves the parent object.
| 归档时间: |
|
| 查看次数: |
3428 次 |
| 最近记录: |