2014-07-04 45 views
1

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

Story.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; 
    ... 

Comment.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(故事)执行:

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
  • 春数据JPA 1.6.0

回答

2

这是使用单向袋的预期行为。根据[休眠反模式] [1]:

袋语义有表现最差的,当涉及到的 数量的操作,因为它总是重新创建整个集合。 Hibernate发出删除语句以从关联表中删除旧集合的所有关联。然后,它发出N个插入 以将表示新集合的所有关联添加到 关联表中。休眠不会分析集合中有多少个元素已被更改 。

  1. 你可以把它变成一个ID包,这是一个索引列表优化。
  2. 您可以将具有2个@ManyToOne关联的UserComment映射映射到Story和Comment,这样您的包就会变成一个mappedBy双向包,比单向包更有效率(因为mappedBy包不会控制关联,因为它将@ManyToOne方传播到SQL语句的状态转换)。
+0

我是唯一一个认为,有这么多问题,我们应该没有hibernate管理的关联更好?我将编写一个简单的本地查询来将注释添加到列表中。 – xtian

+1

我的建议是保持简单。 –

+0

就像编写我自己的查询一样简单,为什么我应该更改我的模型以适应持久性引擎特性? @Query(value =“insert into UserComment(Story_id,Comment_id)VALUES(:storyId,:commentId)”,nativeQuery = true) – xtian

相关问题