一尘不染

尝试保存数据时找不到实体..

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> {}

阅读 333

收藏
2020-05-30

共1个答案

一尘不染

尝试这个

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

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

2020-05-30