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
我是唯一一个认为,有这么多问题,我们应该没有hibernate管理的关联更好?我将编写一个简单的本地查询来将注释添加到列表中。 – xtian
我的建议是保持简单。 –
就像编写我自己的查询一样简单,为什么我应该更改我的模型以适应持久性引擎特性? @Query(value =“insert into UserComment(Story_id,Comment_id)VALUES(:storyId,:commentId)”,nativeQuery = true) – xtian