11

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> {}
FakeLion
  • 147
  • 1
  • 1
  • 9

1 Answers1

26

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.

pvpkiran
  • 25,582
  • 8
  • 87
  • 134