レコードがデータベースに2回投稿される理由を教えてください。おもう。これは、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;
}