Heim > Fragen und Antworten > Hauptteil
Ich versuche, 6 Kommentare in der Kommentartabelle der Datenbank zu behalten, indem ich einen Fremdschlüssel für die Beitrags-ID verwende, aber die letzten 3 Kommentare überschreiben die ersten 3 Kommentare mit dem neu hinzugefügten Fremdschlüssel.
Testkategorie:
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);
P粉0381618732024-04-02 11:19:49
您总共创建了 3 个评论实例(因此数据库表中有 3 条记录),而不是每个帖子 3 个实例。
当您更新 post1 评论时,您会将 post2 评论作为参数,因此从 comments 到 post2 的外键将更改为 post1。
如果您希望每个帖子有 3 条评论,则总共需要 6 个评论实例(2 个帖子 * 3 条评论)。
P粉1876770122024-04-02 00:07:37
发生这种情况是因为您放置了相同的注释对象,然后 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())); ArrayListarrayList = 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);
这样就创建了另外三个对象用于评论。