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;
}
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";
}
The service :
public void saveTopic(Topic topic) {
topicRepository.save(topic);
}
The repository :
public interface TopicRepository extends JpaRepository<Topic,String> {}
Combining @NotFound(action = NotFoundAction. IGNORE) with @ManyToOne annotation will stop the persistence provider from throwing the EntityNotFoundException, but we'll have to handle missing entity by hand to avoid NullPointerException.
Class EntityNotFoundExceptionThrown by the persistence provider when an entity reference obtained by EntityManager. getReference is accessed but the entity does not exist. Thrown when EntityManager. refresh is called and the object no longer exists in the database.
Try this
@OneToMany(mappedBy = "topicId", cascade = {CascadeType.ALL})
private Set<Message> messages;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With