0

你能告诉我,为什么记录会在数据库中发布两次。我认为。发生这种情况是因为我使用了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;
}
4

1 回答 1

0

在这种具体情况下,您不需要保存主服务器和客户端。

  • 保存主服务器或客户端就足够了(使用此具体映射)

但我认为主要问题是你没有一个好的 equals 方法,Comment所以你的 ORM 提供者认为有两个不同的评论,因此将它们存储两次。

于 2012-08-29T07:57:25.363 回答