【问题标题】:Why the record is posted twice in the database?为什么记录在数据库中发布两次?
【发布时间】:2012-08-23 18:15:03
【问题描述】:

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

【问题讨论】:

    标签: spring spring-mvc spring-data-jpa


    【解决方案1】:

    在这个具体的例子中,你不需要保存master和client。

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

    但我认为主要问题是您的 Comment 中没有好的 equals 方法,因此您的 ORM 提供者认为有两个不同的 cmets,因此将它们存储两次。

    【讨论】:

    • 就我而言,保存master或者client就足够了
    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    相关资源
    最近更新 更多