【问题标题】:Unable find Entity .. while trying to save data尝试保存数据时找不到实体..
【发布时间】:2018-06-08 05:40:55
【问题描述】:

当我尝试保存带有消息的主题时遇到此异常: 嵌套异常是 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> {}

【问题讨论】:

    标签: hibernate jpa spring-boot


    【解决方案1】:

    试试这个

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

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

    【讨论】:

    • 有效!我之前尝试过 cascade = {CascadeType.PERSIST} ,但没有成功,所以我没有尝试 CascadeType.ALL ,谢谢。
    • 为什么 CasadeType.PERSIST 不起作用?似乎只是在坚持。 @pvpkiran
    • 遇到了同样的问题,我不想全部添加。出于某种原因,添加 CascadeType.MERGE 会有所帮助
    • @Alan Sereb 我有同样的情况,合并工作但坚持没有。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    相关资源
    最近更新 更多