gpt4 book ai didi

java - Hibernate 添加到 List 时重新创建连接表

转载 作者:行者123 更新时间:2023-11-29 03:19:29 24 4
gpt4 key购买 nike

我有一个包含 Comment 列表的 Story,用 JoinTable 映射。我注意到每次我向列表中添加新评论时,hibernate 都会删除并重新创建连接表中与故事相关的所有条目。我希望它只是向表中添加一个新行。在下面的代码中,保存方法由 Spring Data 实现。我错过了什么吗?谢谢。

故事.java:

@Entity
public class Story implements Serializable {
@OneToMany
@JoinTable(name="UserComment", joinColumns = @JoinColumn(name = "Story_id"), inverseJoinColumns = @JoinColumn(name = "Comment_id"))
private List<Comment> userComments;
...

注释.java:

@Entity
public class Comment implements Serializable {
...

添加新评论:

Comment comment = new Comment();
comment.setContent(content);
commentRepository.save(comment);
story.getUserComments().add(comment);
storyRepository.save(story);

Hibernate 记录 storyRepository.save(story) 执行:

Hibernate: delete from UserComment where Story_id=?
Hibernate: insert into UserComment (Story_id, Comment_id) values (?, ?)
Hibernate: insert into UserComment (Story_id, Comment_id) values (?, ?)
Hibernate: insert into UserComment (Story_id, Comment_id) values (?, ?)
Hibernate: insert into UserComment (Story_id, Comment_id) values (?, ?)
Hibernate: insert into UserComment (Story_id, Comment_id) values (?, ?)
Hibernate: insert into UserComment (Story_id, Comment_id) values (?, ?)
Hibernate: insert into UserComment (Story_id, Comment_id) values (?, ?)

库版本:

  • hibernate 4.3.5
  • Spring 数据 JPA 1.6.0

最佳答案

这是所用单向包的预期行为。根据 [Hibernate 反模式][1]:

The bag semantics has the worst performance when it comes to the number of operations since it always re-creates the entire collection. Hibernate issues a delete statement to remove all associations of the old collection from the association table. Then, it issues N inserts to add all associations representing the new collection to the association table. Hibernate does not analyze how many elements have been changed in the collection.

  1. 您可以通过将它变成一个 id-bag 来优化它,它是一个索引列表。
  2. 您可以将具有 2 个@ManyToOne 关联的 UserComment 映射映射到 Story 和 Comment,因此您的包将变成一个 mappedBy 双向包,这比它的单向对应包更有效(因为 mappedBy 包不会控制关联,因为它将是@ManyToOne 端将状态转换传播到 SQL 语句)。

关于java - Hibernate 添加到 List 时重新创建连接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24580527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com