无法找到实体..当试图保存数据

我收到这个异常,当我试图用消息保存主题: 嵌套异常是javax.persistence.EntityNotFoundException:无法找到带有id的mypackage.model.Message 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;

当你没有指定的CascadeType,那么框架认为话题对象内部的消息你要保存的已经保存在数据库中,并尝试在Messages表中搜索这些消息,以便它可以将它与要保存在Topic表中的主题对象相关联。
如果指定级联类型,则它会保存所有子对象,然后保存父对象。

以上是 无法找到实体..当试图保存数据 的全部内容, 来源链接: utcz.com/qa/265947.html

回到顶部