尝试保存数据时找不到实体.. [英] Unable find Entity .. while trying to save data

查看:51
本文介绍了尝试保存数据时找不到实体..的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试通过消息保存主题时出现此异常: 嵌套的异常是javax.persistence.EntityNotFoundException:无法找到ID为fb8d39ea-0094-410d-975a-ea4495781422的mypackage.model.Message

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

这是模型:

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

推荐答案

尝试一下

 @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.

这篇关于尝试保存数据时找不到实体..的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆