gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:06:34 25 4
gpt4 key购买 nike

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

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

服务:

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;

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

关于hibernate - 尝试保存数据时无法找到实体..,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47994519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com