0

レコードがデータベースに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;
}
4

1 に答える 1

0

この具体的なケースでは、マスターとクライアントを保存する必要はありません。

  • マスターまたはクライアントを保存するだけで十分です(この具体的なマッピングを使用)

しかし、主な問題は、適切なequalsメソッドがないCommentため、ORMプロバイダーが2つの異なるコメントがあると考え、それらを2回保存することだと思います。

于 2012-08-29T07:57:25.363 に答える