我試圖在資料庫(kù)的 Comment 表中使用帖子 id 的外鍵保留 6 條評(píng)論,但最後 3 條評(píng)論使用新添加的外鍵覆蓋了前 3 條評(píng)論。
測(cè)試類別:
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);
您總共建立了 3 個(gè)評(píng)論實(shí)例(因此資料庫(kù)表中有 3 筆記錄),而不是每個(gè)貼文 3 個(gè)實(shí)例。
當(dāng)您更新 post1 評(píng)論時(shí),您會(huì)將 post2 評(píng)論作為參數(shù),因此從 comments 到 post2 的外鍵將變更為 post1。
如果您希望每個(gè)貼文有 3 則評(píng)論,則總共需要 6 個(gè)評(píng)論實(shí)例(2 個(gè)貼文 * 3 則評(píng)論)。
發(fā)生這種情況是因?yàn)槟胖昧讼嗤脑]釋對(duì)象,然後 hibernate 認(rèn)為您想要將註釋的連接從 post2
更改為 post1
。
因此您必須重新建構(gòu)這三個(gè)註解。
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);
這樣就創(chuàng)建了另外三個(gè)物件用於評(píng)論。