我试图在数据库的 Comment 表中使用帖子 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); Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您总共创建了 3 个评论实例(因此数据库表中有 3 条记录),而不是每个帖子 3 个实例。
当您更新 post1 评论时,您会将 post2 评论作为参数,因此从 comments 到 post2 的外键将更改为 post1。
如果您希望每个帖子有 3 条评论,则总共需要 6 个评论实例(2 个帖子 * 3 条评论)。
发生这种情况是因为您放置了相同的注释对象,然后 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 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(), 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);
这样就创建了另外三个对象用于评论。