トピックとコメントを含む簡単なWebアプリを作成しようとしています。トピックモデル:
@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 List<Comment> comments;
// We shouldn't read whole collection to get this basic info
private int commentsCount;
private Date timeLastUpdated;
/**
* Removes comment from the Topic entity
* @param comment
*/
public void removeComment(Comment comment) {
// updating topic
timeLastUpdated = Utils.getCurrentTime();
commentsCount--;
comments.remove(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;
}
コメントサービス:
@Service
@Transactional
public class CommentService {
@Autowired
private CommentRepository commentRepository;
public int saveComment(Comment comment){
return commentRepository.save(comment).getId();
}
public Comment findCommentByID(int id){
return commentRepository.findOne(id);
}
/**
* Deletes a comment
* @param comment -- a comment to delete
* @return id of a topic
*/
public int deleteComment(Comment comment) {
int result = comment.getTopic().getId();
commentRepository.delete(comment);
return result;
}
}
コメントを削除しているコントローラーのメソッド:
@RequestMapping(value = "/deleteComment/{commentId}", method = {RequestMethod.POST, RequestMethod.GET} )
public String deleteComment(@PathVariable int commentId, @ModelAttribute("comment")Comment comment, BindingResult result, Model model){
Topic parentTopic;
Comment deletedComment = commentService.findCommentByID(commentId);
if (deletedComment != null) {
// remove any relations
parentTopic = deletedComment.getTopic();
parentTopic.removeComment(deletedComment);
// rempve the comment itself
commentService.deleteComment(deletedComment);
}
//return "refresh:";
return "home";
}
削除されたエンティティが永続化に渡されました:[com.epam.mvc3.model.Comment#]