一对多映射Hibernate



我试图在数据库中的评论表中使用post id的外键保存6条评论,但最后3条评论用新添加的外键覆盖了前3条评论。

测试类:

Comments comments = new Comments("1st Comment", new Date(System.currentTimeMillis()));
Comments comments2 = new Comments("2st Comment", new Date(System.currentTimeMillis()));
Comments comments3 = new Comments("3st Comment", new Date(System.currentTimeMillis()));
ArrayList<Comments> arrayList = new ArrayList<>();
arrayList.add(comments);
arrayList.add(comments2);
arrayList.add(comments3);
// Insert Without Comment
Post post1 = new Post("1st Post", "1st Post Description", new ArrayList<Comments>(), new Date(System.currentTimeMillis()));
postReposetory.save(post1);
// Insert With Comment
Post post2 = new Post("2st Post", "2st Post Description", arrayList, new Date(System.currentTimeMillis()));
postReposetory.save(post2);
// Update (Insert Comment)
post1.setComments(arrayList);
post1.setUpdatedAt(new Date(System.currentTimeMillis()));
postReposetory.save(post1);

发生这种情况是因为您放置了相同的注释对象,然后hibernate考虑您想要将注释的连接从post2更改为post1

因此你必须重新构造三个注释。

Comments comments = new Comments("1st Comment", new Date(System.currentTimeMillis()));
Comments comments2 = new Comments("2st Comment", new Date(System.currentTimeMillis()));
Comments comments3 = new Comments("3st Comment", new Date(System.currentTimeMillis()));
ArrayList<Comments> arrayList = new ArrayList<>();
arrayList.add(comments);
arrayList.add(comments2);
arrayList.add(comments3);
// Insert With Comment
Post post1 = new Post("1st Post", "1st Post Description", new ArrayList<Comments>(), new Date(System.currentTimeMillis()));
postReposetory.save(post1);

// Insert Without Comment
Post post2 = new Post("2st Post", "2st Post Description", arrayList, new Date(System.currentTimeMillis()));
postReposetory.save(post2);
// Update (Insert Comment)
comments = new Comments("1st Comment", new Date(System.currentTimeMillis()));
comments2 = new Comments("2st Comment", new Date(System.currentTimeMillis()));
comments3 = new Comments("3st Comment", new Date(System.currentTimeMillis()));
post1.setComments(List.of(comments, comments2, comments3));
post1.setUpdatedAt(new Date(System.currentTimeMillis()));
postReposetory.save(post1);

以这种方式,为注释创建了另外三个对象。

您总共创建了3个评论实例(因此数据库表中有3条记录),而不是每个帖子3个实例。

当你更新post1的评论时,你给了post2的评论作为参数,所以从comments到post2的外键将改变为post1。

如果你想每篇文章有3条评论,你需要6个评论实例(2篇文章* 3条评论).

最新更新