您能告诉我,为什么记录会在数据库中发布两次。我认为。这是因为我使用 save()方法。但是我不应该单独保存主实体和从属实体吗?
Controller method:
@RequestMapping(value = "/addComment/{topicId}", method = RequestMethod.POST)
public String saveComment(@PathVariable int topicId, @ModelAttribute("newComment")Comment comment, BindingResult result, Model model){
Topic commentedTopic = topicService.findTopicByID(topicId);
commentedTopic.addComment(comment);
// TODO: Add a validator here
if (!comment.isValid() ){
return "//";
}
// Go to the "Show topic" page
commentService.saveComment(comment);
return "redirect:../details/" + topicService.saveTopic(commentedTopic);
}
服务:
@Service
@Transactional
public class CommentService {
@Autowired
private CommentRepository commentRepository;
public int saveComment(Comment comment){
return commentRepository.save(comment).getId();
}
}
@Service
@Transactional
public class TopicService {
@Autowired
private TopicRepository topicRepository;
public int saveTopic(Topic topic){
return topicRepository.save(topic).getId();
}
}
型号:
@Entity
@Table(name = "T_TOPIC")
public class Topic {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@ManyToOne
@JoinColumn(name="USER_ID")
private User author;
@Enumerated(EnumType.STRING)
private Tag topicTag;
private String name;
private String text;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "topic", cascade = CascadeType.ALL)
private Collection<Comment> comments = new LinkedHashSet<Comment>();
}
@Entity
@Table(name = "T_COMMENT")
public class Comment
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@ManyToOne
@JoinColumn(name="TOPIC_ID")
private Topic topic;
@ManyToOne
@JoinColumn(name="USER_ID")
private User author;
private String text;
private Date creationDate;
}
答案 0 :(得分:0)
在这个具体案例中,您不需要保存主服务器和客户端。
但我认为主要的问题是你的Comment
中没有一个好的等号方法,所以你的ORM提供者认为有两个不同的注释,因此存储它们两次。