在尝试保存数据时无法找到实体..

时间:2017-12-27 15:16:22

标签: hibernate jpa spring-boot

当我尝试使用消息保存主题时,我收到此异常: 嵌套异常是javax.persistence.EntityNotFoundException:无法找到id为fb8d39ea-0094-410d-975a-ea4495781422的mypackage.model.Message

以下是模型:

@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;
}

控制器:

@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";
    }

服务:

public void saveTopic(Topic topic) {
        topicRepository.save(topic);
}

存储库:

public interface TopicRepository extends JpaRepository<Topic,String> {}

1 个答案:

答案 0 :(得分:3)

试试这个

 @OneToMany(mappedBy = "topicId", cascade = {CascadeType.ALL})
 private Set<Message> messages;

当您未指定cascadeType时,框架会认为您要保存的主题对象中的消息已保存在数据库中,并尝试在Messages表中搜索这些消息,以便它可以将其与主题对象即将保存在主题表中 如果指定级联类型,则保存所有子对象,然后保存父对象。