[英]Doesn't receive updated data from the database (Spring OneToMany relationship)
I'm new to java and now I'm writing a simple website for learning.我是 java 的新手,现在我正在编写一个简单的学习网站。 I ran into this problem:
我遇到了这个问题:
User entity:用户实体:
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Message> messages;
Message entity:消息实体:
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id")
private User author;
Controller: Controller:
Set<Message> messages = user.getMessages();
model.addAttribute("messages", messages);
And when I get the data for the first time (with getMessages ), everything works fine.当我第一次(使用getMessages )获取数据时,一切正常。 But after adding a Message, this function returns the same Set without a new Message.
但是添加Message之后,这个function返回同样的Set,没有新的Message。 Although an entry in the database appears and if called:
尽管出现了数据库中的条目并且如果调用:
messages = messageRepo.findAll();
the new Message appears in the list.新消息出现在列表中。 After restarting the server, a new article appears in the method getMessages .
重启服务器后, getMessages方法中会出现一篇新文章。 What is my fault, why is the data not updated after adding the new Message?
我怎么了,为什么添加新消息后数据没有更新?
UPD:升级版:
Code for adding a Message:添加消息的代码:
@PostMapping("/main")
public String add(
@AuthenticationPrincipal User user,
@Valid Message message,
BindingResult bindingResult,
Model model
) throws IOException {
message.setAuthor(user);
if (bindingResult.hasErrors()) {
Map<String, String> errorsMap = ControllerUtils.getErrors(bindingResult);
model.mergeAttributes(errorsMap);
model.addAttribute("message", message);
} else {
model.addAttribute("message", null);
messageRepo.save(message);
}
return "main";
}
It seems that you add the author to the message but you didn't do the same thing for author:似乎您将作者添加到消息中,但您没有为作者做同样的事情:
For exemple add a new method in Author class for adding a new message:例如在作者 class 中添加一个新方法来添加新消息:
public class Author {
...
public void addMessage(Message message){
if(messages==null) messages= new HashSet();
messages.add(message);
}
...
}
and use it in your code like this:并在您的代码中使用它,如下所示:
author.addMessage(message);
Note that you should define the hashCode method otherwise the HashSet will ignore the new messages.请注意,您应该定义 hashCode 方法,否则 HashSet 将忽略新消息。
Also If you don't have any constraint to use a bi-directional relation it would be better to use a uni-directional relation only (message -> author).此外,如果您对使用双向关系没有任何限制,那么最好只使用单向关系(消息->作者)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.